help.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { hexStr2byteArray } from './code.js';
  2. import { ADDRESS_PREFIX } from './address.js';
  3. import { getBase58CheckAddress, decodeBase58Address } from './crypto.js';
  4. import { byteArray2hexStr } from './bytes.js';
  5. export function hexStringToBase58(sHexString: string) {
  6. if (sHexString.length < 2 || (sHexString.length & 1) != 0) return '';
  7. const bytes = hexStr2byteArray(sHexString);
  8. return getBase58CheckAddress(bytes);
  9. }
  10. export function base58ToHexString(sBase58: string) {
  11. const bytes = decodeBase58Address(sBase58);
  12. if (!bytes) return '';
  13. return byteArray2hexStr(bytes);
  14. }
  15. export function hexStringToUtf8(hex: string) {
  16. const arr = hex.split('');
  17. let out = '';
  18. for (let i = 0; i < arr.length / 2; i++) {
  19. const tmp = `0x${arr[i * 2]}${arr[i * 2 + 1]}`;
  20. const charValue = String.fromCharCode(parseInt(tmp));
  21. out += charValue;
  22. }
  23. return out;
  24. }
  25. export function stringUtf8tHex(str: string) {
  26. let val = '';
  27. for (let i = 0; i < str.length; i++) {
  28. if (val == '') val = str.charCodeAt(i).toString(16);
  29. else val += str.charCodeAt(i).toString(16);
  30. }
  31. return val;
  32. }
  33. export function address2HexString(sHexAddress: string) {
  34. if (sHexAddress.length == 42 && sHexAddress.indexOf(ADDRESS_PREFIX) == 0) return sHexAddress;
  35. return base58ToHexString(sHexAddress);
  36. }
  37. export function hexString2Address(sAddress: string) {
  38. return hexStringToBase58(sAddress);
  39. }
  40. export function hexString2Utf8(sHexString: string) {
  41. return hexStringToUtf8(sHexString);
  42. }
  43. export function stringUtf8toHex(sUtf8: string) {
  44. return stringUtf8tHex(sUtf8);
  45. }