Skip to content

Instantly share code, notes, and snippets.

@donma
Created February 10, 2025 06:33
Show Gist options
  • Select an option

  • Save donma/e63c7a395b92e1b701da95fae3157752 to your computer and use it in GitHub Desktop.

Select an option

Save donma/e63c7a395b92e1b701da95fae3157752 to your computer and use it in GitHub Desktop.
//C
static string ConvertHexToBase58Check(string hexAddress)
{
byte[] addressBytes = HexToBytes(hexAddress);
// 計算雙重 SHA-256 校驗碼
using (SHA256 sha256 = SHA256.Create())
{
byte[] hash1 = sha256.ComputeHash(addressBytes);
byte[] hash2 = sha256.ComputeHash(hash1);
// 取前 4 位作為校驗碼
byte[] checksum = hash2.Take(4).ToArray();
// 拼接地址與校驗碼
byte[] addressWithChecksum = addressBytes.Concat(checksum).ToArray();
// 轉換為 Base58
return EncodeBase58(addressWithChecksum);
}
}
static byte[] HexToBytes(string hex)
{
return Enumerable.Range(0, hex.Length / 2)
.Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16))
.ToArray();
}
static string EncodeBase58(byte[] input)
{
var Base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var intData = new BigInteger(input.Reverse().Concat(new byte[] { 0 }).ToArray());
string result = "";
while (intData > 0)
{
int remainder = (int)(intData % 58);
intData /= 58;
result = Base58Chars[remainder] + result;
}
// 保留前導 0
foreach (byte b in input)
{
if (b == 0) result = '1' + result;
else break;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment