Skip to content

Instantly share code, notes, and snippets.

@btnguyen2k
Created November 14, 2024 13:25
Show Gist options
  • Select an option

  • Save btnguyen2k/fb8f8d7803aaad0efb61d7c2a0736124 to your computer and use it in GitHub Desktop.

Select an option

Save btnguyen2k/fb8f8d7803aaad0efb61d7c2a0736124 to your computer and use it in GitHub Desktop.
[C#] Chuyển số thập nhân sang cơ số 32 - http://goclaptrinh.io/cms/beginner/csharp-crockford-base32-numbers/
using System;
class GocLapTrinh
{
static int NhapSoThapPhan()
{
Console.Write("Nhap so thap phan: ");
return int.Parse(Console.ReadLine() ?? string.Empty);
}
static string NhapSoBase32()
{
Console.Write("Nhap so o he co so 32 (bang ma Crockford Base32): ");
return Console.ReadLine() ?? string.Empty;
}
static string DoiSangBase32(int n)
{
var base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
var s = "";
while (n > 0)
{
s = base32[n % 32] + s;
n /= 32;
}
return s;
}
static int DoiSangThapPhan(string s)
{
var base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
var n = 0;
s = s.ToUpper().Replace('I', '1').Replace('L', '1').Replace('O', '0').Replace('U', 'V');
foreach (var c in s)
{
var i = base32.IndexOf(c);
if (i == -1) return -1; // co ky tu khong hop le!
n = n * 32 + i;
}
return n;
}
static void Main()
{
var n = NhapSoThapPhan();
Console.WriteLine($"So thap phan: {n}, doi sang base32: {DoiSangBase32(n)}");
var s = NhapSoBase32();
Console.WriteLine($"So base32: {s}, doi sang thap phan: {DoiSangThapPhan(s)}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment