Java整数到字节数组短

Edward Banfa :

我正在尝试将Integer转换为字节数组(4个字节的数组),然后提取每个字节的后4位,然后从每个字节的后4位创建一个short。

我有以下代码,但它始终显示零。


    private static short extractShort(byte[] byteArray) {
        short s = 1;
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        for(int i = 0; i < byteArray.length; i++) {
            byte lastFourBytes = extractLast4Bits(byteArray[i]);
            // Uses a bit mask to extract the bits we are interested in
            byteBuffer.put(lastFourBytes);
        }
       return  ByteBuffer.wrap(byteBuffer.array()).getShort();
    }


    private static byte extractLast4Bits(byte byteParam) {
        return  (byte) ( byteParam & 0b00001111);
    }

    private static byte[] intToByteArray(int i) {
        return new byte[] {
            (byte)((i >> 24) & 0xff),
            (byte)((i >> 16) & 0xff),
            (byte)((i >> 8) & 0xff),
            (byte)((i >> 0) & 0xff),
         };
    }

}

任何帮助将由衷的感谢

WJS:

一旦获得字节数组,请尝试此操作。


    short val = 0;
    for (byte b : bytes) {
       val <<= 4;
       val |= (b&0xf)
    }

如果您要从开始做int,可以这样。

      int v = 0b1110_1010_1111_1001_1010_1000_1010_0111;
      short verify = (short) 0b1010_1001_1000_0111;
      // initialize a short value
      short val = 0;

      // increment from 24 to 0 by 8's  the loop will
      // repeat 4 times.
      for (int i = 24; i >= 0; i -= 8) {
         // start by shifting the result left 4 bits
         // first time thru this does nothing.
         val <<= 4;

         // Shift the integer right by i bits (first time is
         // 24, next time is 16, etc
         // then mask off the lower order 4 bits of the right
         // most byte and OR it to the result(val).
         // then when the loop continues, val will be
         // shifted left 4 bits to allow for the next "nibble"

         val |= ((v >> i) & 0xf);
      }
      System.out.println(val);
      System.out.println(verify);

有关按位运算符的更多信息,请查看此Wikipedia链接。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章