写在NSData (Objective-c)中的NSUInteger不能转换为integer (Java)



我正在尝试读取一个用Objective-C编写的二进制文件,像这样:

u_int32_t test = 71508;
NSMutableData * outputData = [ [ NSData dataWithBytes:&test length:sizeof( u_int32_t ) ] mutableCopy ];
// Saves the data
...
// Then reading the value works fine
u_int32_t test;
[ self getBytes:&test length:sizeof( u_int32_t ) ];

然后我试图在Java中读取int:

// Read the file
...
Bytes ObjCBytes = byteArrayOutputStream.toByteArray( );
...
// Try to convert my Objective-C byte array to an int :
ByteBuffer buffer = ByteBuffer.allocate( 4 );
buffer.put( ObjCBytes );
buffer.flip( );
int ObjCInt = buffer.getInt( );

但是我没有得到相同的结果!

所以,我决定在Java中做同样的事情:

ByteBuffer buffer = ByteBuffer.allocate( 4 );
buffer.putInt( 71508 );
bytes javaBytes = buffer.array( );

这两个字节数组似乎是颠倒的:

ObjCBytes: {84,23,1,0}

javaBytes: {0,1,23,84}

无论整数值如何,行为都是相同的。

对不起:我是新手…我相信原因是Java没有unsigned int ?

我试了很多答案,但还没有找到解决办法。

如何将字节数组转换为整数而不管用于编写它的语言?

非常感谢您的帮助

据我所知,NSData默认使用little_endian字节顺序,而Java使用big_endian字节顺序。

维基百科的更多信息

我决定将我的NSData转换为big_endian,以便它可以在Java中读取:

NSUInteger    test = 71508;
// Java compatibility
u_int32_t bigEndianTest = CFSwapInt32BigToHost( test );
// Writes the value
NSMutableData * outputData = [ [ NSData dataWithBytes:&bigEndianTest length:saltSize ] mutableCopy ];

根据需要,也可以反过来(Java => Little Endian => Objective-C)

最新更新