简体   繁体   English

使用ByteBuffer在Java中发布复制字节字符串

[英]Issue replicating byte string in Java with ByteBuffer

I'm trying to duplicate a byte String that I produce in Objective-C (on iOS) in Java but am having trouble. 我正在尝试复制Java中在Objective-C(在iOS上)中生成的字节字符串,但遇到了麻烦。 Here's the string I want to produce: 这是我要产生的字符串:

"\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

I get that string from an array of 4 integers - [1,1,0,0] - where each integer has 4 bytes. 我从4个整数数组[1,1,0,0]获得该字符串,其中每个整数都有4个字节。 After looking at a bunch of questions on here, I've attempted constructing that string in Java using ByteBuffer as follows: 在查看了一系列问题之后,我尝试使用ByteBuffer在Java中构造该字符串,如下所示:

ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putInt(1);
bytes.putInt(1);
bytes.putInt(0);
bytes.putInt(0);

String byteString = new String(bytes.array());

However that gives me: 但是,这给了我:

"\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"

When I unpack that, the array of ints I get is [16777216, 16777216, 0, 0] . 当我打开[16777216, 16777216, 0, 0]得到的整数数组是[16777216, 16777216, 0, 0] Obviously I'm doing something wrong, and I'm hoping someone can point me in the right direction. 显然我做错了事,希望有人能指出我正确的方向。

iOS is little-endian, so the least significant byte of a 4-byte integer comes first. iOS是低位字节序,因此4字节整数的最低有效字节排在第一位。

Java ByteBuffer defaults to big-endian , so the opposite applies. Java ByteBuffer 默认为big-endian ,因此情况相反。

The initial order of a byte buffer is always BIG_ENDIAN 字节缓冲区的初始顺序始终为BIG_ENDIAN

You can change this with 您可以使用

bytes.order(ByteOrder.LITTLE_ENDIAN);

What you want is: 您想要的是:

ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putInt(16777216);
bytes.putInt(16777216);
bytes.putInt(0);
bytes.putInt(0);

String byteString = new String(bytes.array());

The endianness of the platforms are different, so when you put 4 bytes in, the bytes are reversed. 平台的字节顺序不同,因此当您放入4个字节时,这些字节将反转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM