Java中的字节数组和Int转换

我在使用这两个功能时遇到了一些困难:byteArrayToInt和intToByteArray。


问题是,如果我使用一个来到达另一个,而使用那个结果去到达前一个,则结果是不同的,如下面的示例所示。


我在代码中找不到错误。任何想法都非常欢迎。谢谢。


public static void main(String[] args)

{

    int a = 123;

    byte[] aBytes = intToByteArray(a);

    int a2 = byteArrayToInt(aBytes);


    System.out.println(a);         // prints '123'

    System.out.println(aBytes);    // prints '[B@459189e1'

    System.out.println(a2);        // prints '2063597568

            System.out.println(intToByteArray(a2));  // prints '[B@459189e1'

}


public static int byteArrayToInt(byte[] b) 

{

    int value = 0;

    for (int i = 0; i < 4; i++) {

        int shift = (4 - 1 - i) * 8;

        value += (b[i] & 0x000000FF) << shift;

    }

    return value;

}


public static byte[] intToByteArray(int a)

{

    byte[] ret = new byte[4];

    ret[0] = (byte) (a & 0xFF);   

    ret[1] = (byte) ((a >> 8) & 0xFF);   

    ret[2] = (byte) ((a >> 16) & 0xFF);   

    ret[3] = (byte) ((a >> 24) & 0xFF);

    return ret;

}


慕桂英4014372
浏览 547回答 3
3回答

弑天下

您正在两种方法之间交换字节序。您已将intToByteArray(int a)的低位分配给ret[0],但随后byteArrayToInt(byte[] b)又将b[0]结果的高位分配了。您需要反转其中一个,例如:public static byte[] intToByteArray(int a){&nbsp; &nbsp; byte[] ret = new byte[4];&nbsp; &nbsp; ret[3] = (byte) (a & 0xFF);&nbsp; &nbsp;&nbsp; &nbsp; ret[2] = (byte) ((a >> 8) & 0xFF);&nbsp; &nbsp;&nbsp; &nbsp; ret[1] = (byte) ((a >> 16) & 0xFF);&nbsp; &nbsp;&nbsp; &nbsp; ret[0] = (byte) ((a >> 24) & 0xFF);&nbsp; &nbsp; return ret;}

慕桂英546537

这需要做很多工作:public static int byteArrayToLeInt(byte[] b) {&nbsp; &nbsp; final ByteBuffer bb = ByteBuffer.wrap(b);&nbsp; &nbsp; bb.order(ByteOrder.LITTLE_ENDIAN);&nbsp; &nbsp; return bb.getInt();}public static byte[] leIntToByteArray(int i) {&nbsp; &nbsp; final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);&nbsp; &nbsp; bb.order(ByteOrder.LITTLE_ENDIAN);&nbsp; &nbsp; bb.putInt(i);&nbsp; &nbsp; return bb.array();}此方法使用Java ByteBuffer和程序包中的ByteOrder功能java.nio。在需要可读性的地方,此代码应该是首选。它也应该很容易记住。我在这里显示了Little Endian字节顺序。要创建Big Endian版本,您只需忽略对的调用order(ByteOrder)。在性能优先于可读性的代码中(大约快10倍):public static int byteArrayToLeInt(byte[] encodedValue) {&nbsp; &nbsp; int value = (encodedValue[3] << (Byte.SIZE * 3));&nbsp; &nbsp; value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2);&nbsp; &nbsp; value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1);&nbsp; &nbsp; value |= (encodedValue[0] & 0xFF);&nbsp; &nbsp; return value;}public static byte[] leIntToByteArray(int value) {&nbsp; &nbsp; byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE];&nbsp; &nbsp; encodedValue[3] = (byte) (value >> Byte.SIZE * 3);&nbsp; &nbsp; encodedValue[2] = (byte) (value >> Byte.SIZE * 2);&nbsp; &nbsp;&nbsp; &nbsp; encodedValue[1] = (byte) (value >> Byte.SIZE);&nbsp; &nbsp;&nbsp; &nbsp; encodedValue[0] = (byte) value;&nbsp; &nbsp; return encodedValue;}只需反转字节数组索引以从零计数到三即可创建此代码的Big Endian版本。笔记:在Java 8中,您还可以使用Integer.BYTES常量,该常量比更为简洁Integer.SIZE / Byte.SIZE。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java