[实用程序源码及工具软件] HotCRC内的Base64ToHex()源码

[复制链接]
 楼主| hotpower 发表于 2023-9-23 09:53 | 显示全部楼层 |阅读模式
本帖最后由 hotpower 于 2023-9-23 09:54 编辑

菜农电子淘宝:https://hotcomlock.taobao.com/ 准备出书:http://hotcomlock.com/hotcomlock.html
  1.     function Base64ToHex(hexstring)
  2.     {
  3.         var i, hexstr;
  4.         hexstr = "";
  5.         for (i = 0; i < hexstring.length; i += 6)
  6.         {
  7.             hexstr += Base64ToHexStr(hexstring.substr(i, 6));
  8.         }
  9.         return hexstr;//输出4N个字符
  10.     }
  1.     function Base64ToHexStr(hexstr)
  2.     {
  3.         var i, len, c, a, t, x1, x2, x3, x4, encode, hexstring;
  4.         var basestr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5.         len = Math.min(hexstr.length, 6);//输入3个字节
  6.         encode = hexstr.substr(0, 6);
  7.         hexstring = "";
  8.         for (i = len; i < 6; i ++)
  9.         {
  10.             encode += "0";
  11.         }
  12.         if(len & 1) len ++;
  13.         c = hextoint(encode.substr(0, 2));
  14.         a = hextoint(encode.substr(2, 2));
  15.         t = hextoint(encode.substr(4, 2));
  16.         if(len == 6) {
  17.             x1 = c >>> 2;
  18.             x2 = ((c & 0x03) << 4) | (a >>> 4);
  19.             x3 = ((a & 0x0f) << 2) | (t >>> 6);
  20.             x4 = t & 0x3f;
  21.             hexstring  = inttohex(basestr.charCodeAt(x1), 2);
  22.             hexstring  += inttohex(basestr.charCodeAt(x2), 2);
  23.             hexstring  += inttohex(basestr.charCodeAt(x3), 2);
  24.             hexstring  += inttohex(basestr.charCodeAt(x4), 2);
  25.         }
  26.         else if(len == 4) {
  27.             x1 = c >>> 2;
  28.             x2 = ((c & 0x03) << 4) | (a >>> 4);
  29.             x3 = (a & 0x0f) << 2;
  30.             hexstring  = inttohex(basestr.charCodeAt(x1), 2);
  31.             hexstring += inttohex(basestr.charCodeAt(x2), 2);
  32.             hexstring += inttohex(basestr.charCodeAt(x3), 2);
  33.             hexstring += inttohex(basestr.charCodeAt(64), 2);//=
  34.         }
  35.         else if(len == 2) {
  36.             x1 = c >>> 2;
  37.             x2 = (c & 0x03) << 4;
  38.             hexstring  = inttohex(basestr.charCodeAt(x1), 2);
  39.             hexstring += inttohex(basestr.charCodeAt(x2), 2);
  40.             hexstring += inttohex(basestr.charCodeAt(64), 2);//=
  41.             hexstring += inttohex(basestr.charCodeAt(64), 2);//=
  42.         }
  43.         return hexstring;//输出4个字符
  44.     }


快乐制造机 发表于 2025-4-2 10:28 | 显示全部楼层
通过分块处理和字符映射来实现,逻辑很清晰
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:[url=http://www.21ic.com/tools/HotWC3_V1.23.html]

1460

主题

21619

帖子

508

粉丝
快速回复 在线客服 返回列表 返回顶部