dpli36193 2014-04-10 00:46
浏览 42
已采纳

Java语言按位左移的字节序问题

I am trying to translate this simple function from Go to Javascript:

func ShiftLeft(b []byte) []byte {
    l := len(b)
    if l == 0 {
        panic("shiftLeft requires a non-empty buffer.")
    }

    output := make([]byte, l)

    overflow := byte(0)
    for i := int(l - 1); i >= 0; i-- {
        output[i] = b[i] << 1
        output[i] |= overflow
        overflow = (b[i] & 0x80) >> 7
    }

    return output
}

My first attempt was this:

function makeEmpty(size) {


  var result = [];

  for (var i = 0; i < size; i++) {
    result.push(0x00);
  }

  return result;

}

function shiftLeft (b) {

  var len = b.length;

  if (len == 0) {
    throw 'shiftLeft requires a non-empty buffer';
  }

  var output = makeEmpty(len);

  var overflow = 0;

  for (var i = len - 1; i >= 0; i--) {
    output[i] = b[i] << 1;
    output[i] |= overflow;
    overflow = (b[i] & 0x80) >> 7;
  }

  return output;

}

However, this does not work. Given the following test case:

function fromOctal(str) {

  var bytes = [parseInt(str, 2)];

  return bytes;

}

console.log(shiftLeft(fromOctal("10000000"))

The Javascript version returns [256], but the expected result is "00000000" or [0].

What am I getting wrong here? I think it might have to do with endianness, but I have no idea about how to deal with this kind of issue consistently.

  • 写回答

1条回答 默认 最新

  • dongyi1748 2014-04-10 01:05
    关注

    Your mistake appears to be in assuming that the elements of your array are 8-bit integers, but the result of bitwise operators in JavaScript are 32-bit integers and so the most significant bit remains when you do the left shift.

    I believe that adding a bit mask by changing:

    output[i] = b[i] << 1;
    

    to:

    output[i] = (b[i] << 1) & 0xFF;
    

    should fix your issue.

    http://jsfiddle.net/MTj63/

    As a side note, I think your fromOctal() function should actually be named fromBinary().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图