【问题标题】:Java byte Array to signed IntJava 字节数组到带符号的 Int
【发布时间】:2016-11-06 14:43:39
【问题描述】:

我正在尝试将带符号的 int 变量转换为 3 字节数组并向后转换。

getColorint 函数中,我将 int 值转换为字节数组。效果很好!

    public byte [] getColorByte(int color1){
    byte[] color = new byte[3];
    color[2] = (byte) (color1 & 0xFF);
    color[1] = (byte) ((color1 >> 8) & 0xFF);
    color[0] = (byte) ((color1 >> 16) & 0xFF);
    return color;
    }

但如果我尝试使用 getColorint 函数将字节数组转换回整数:

    public int getColorint(byte [] color){
    int answer = color [2];
    answer += color [1] << 8;
    answer += color [0] << 16;
    return answer;
    }

它只适用于正整数值。

这是调试过程中的屏幕截图:

我的输入 int 值为 -16673281,但我的输出 int 值为 38143

谁能帮帮我?

谢谢:)

【问题讨论】:

标签: java android arrays integer converter


【解决方案1】:

Color 类定义了创建和转换颜色整数的方法。颜色表示为压缩整数,由 4 个字节组成:alpha、red、green、blue。 你应该使用它。

【讨论】:

    【解决方案2】:

    这里的问题是字节是有符号的。当您使用 color[2] == -1 执行 int answer = color[2] 时,答案也是 -1,即 0xffffffff,而您希望它是 255 (0xff)。您可以使用 Guava 的 UnsignedBytes 作为补救措施,或者简单地将 color[i] &amp; 0xff 转换为 int。

    【讨论】:

      【解决方案3】:

      由于颜色以 4 个字节表示,因此您还应该存储一个 alpha 通道。

      来自国际:

      public byte [] getColorByte(int color1){
          byte[] color = new byte[4];
          for (int i = 0; i < 4; i++) {
              color [i] = (byte)(color1 >>> (i * 8));
          }
          return color;
      }
      

      到内部:

      public int getColorInt(byte [] color){
          int res = ((color[0] & 0xff) << 24) | ((color[1] & 0xff) << 16) |
                ((color[2] & 0xff) << 8)  | (color[3] & 0xff);
          return res;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 2013-03-11
        • 1970-01-01
        • 2011-11-01
        • 2017-12-03
        • 1970-01-01
        • 2020-06-03
        相关资源
        最近更新 更多