You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将substr替换为substring后byte2Hex函数失效,求解决办法

问题原因与解决方法

问题核心是**substr和substring的参数逻辑完全不同**:

  • substr(start, length):第二个参数是要提取的字符数量
  • substring(start, end):第二个参数是提取的结束索引(结果不包含该索引的字符)

原代码中substr(x, 1)是取从索引x开始的1个字符,直接替换成substring(x, 1)会导致逻辑错误——如果x大于1,substring会自动交换两个参数,返回从索引1到x的字符,完全不符合需求。


解决方法

有两种可靠的修改方式:

方式一:适配substring的参数逻辑

把substr(x, 1)替换为substring(x, x+1),确保只提取1个字符:

function byte2Hex(n)
{
  var nybHexString = "0123456789ABCDEF";
  const highNibble = (n >> 4) & 0x0F;
  const lowNibble = n & 0x0F;
  return nybHexString.substring(highNibble, highNibble + 1) + nybHexString.substring(lowNibble, lowNibble + 1);
}

方式二:用charAt简化逻辑(更推荐)

因为我们只需要单个位置的字符,直接用charAt(index)更直观,也避免了参数混淆:

function byte2Hex(n)
{
  var nybHexString = "0123456789ABCDEF";
  return nybHexString.charAt((n >> 4) & 0x0F) + nybHexString.charAt(n & 0x0F);
}

内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:05:06