【问题标题】:Java - Can't edit byte array contents? [duplicate]Java - 无法编辑字节数组内容? [复制]
【发布时间】:2015-09-29 20:16:40
【问题描述】:
    byte[] stuffA = {69,96,13,37,-69,-96,-13,-37};
    for(int x = 0; x < stuffA.length; x++){
        if(stuffA[x] < 0){
            System.out.println("Somethin be up yo! ");
            System.out.println("This number be negative! " + (int)stuffA[x]);
            stuffA[x] = (byte)((int)stuffA[x] + 256);
            System.out.println("I added 256 and now stuff is positive yo! " + stuffA[x]);
        }
    }
    return;

当我运行它时,我的输出是:

Somethin be up yo! 
This number be negative! -69
I added 256 and now stuff is positive yo! -69
Somethin be up yo! 
This number be negative! -96
I added 256 and now stuff is positive yo! -96
Somethin be up yo! 
This number be negative! -13
I added 256 and now stuff is positive yo! -13
Somethin be up yo! 
This number be negative! -37
I added 256 and now stuff is positive yo! -37

发生了什么?

【问题讨论】:

  • 你认为一个字节可以存储的值的范围是多少?

标签: java arrays casting byte


【解决方案1】:

引用 Java 语言规范,4.2.1 部分:

整数类型的值是以下范围内的整数:对于byte,从-128 到127(含)。

所以,-69 + 256 = 187 = 0x000000BB 转换为字节是 0xBB = -69。

【讨论】:

    【解决方案2】:

    一个字节的范围在 -128 和 127 之间(-2^7 到 2^7-1)加上 256 就像做 360 度转弯一样。将代码中的 256 更改为 128 会显示不同的结果

    【讨论】:

      【解决方案3】:

      byte 只有 8 位,所以只能容纳 2^8 = 256 个值。它是用 java 签名的,所以值在 [-128,127] 的范围内。

      【讨论】:

        【解决方案4】:

        byte 可以保存 256 个不同的值。如果添加 256,则字节溢出,结果保持不变。 在 java 中,范围是 [-128, 127]。

        【讨论】:

          【解决方案5】:

          字节为8位,整数为32位

          基本看位:

          byte b = -37 等价于 219(int),其二进制为:

          0000 0000 0000 1101 1011
          

          int 256:

          0000 0000 0001 0000 0000
          

          将两者相加将得到 475 的 int 值:

          0000 0000 0001 1101 1011
          

          现在将其转换为字节,即采用 LSB 8 位将是:

          1101 1011
          

          这是-37

          希望这可以解释

          【讨论】:

            【解决方案6】:

            一个字节可以保存256 不同的值,因此当您添加 256 时,您将生成一个 Rol (Rotate left) 8 times,它返回与之前相同的值。

            如果您的愿望是将-69 转换为69,为什么不直接创建stuffA[x] *=-1?

            如果你真的想反转位,你可以使用complement operator(~),stuffA[x] = (byte) ~stuffA[x];,但是由于two's complement form,要获得与previos相同的数字你需要add 1,

            点赞stuffA[x] = (byte) ((~stuffA[x]) + 1);

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-12-28
              • 2013-03-04
              • 1970-01-01
              • 2021-09-26
              • 2019-04-18
              • 2013-05-26
              • 2018-08-07
              • 2013-04-07
              相关资源
              最近更新 更多