NSUInteger 写入 NSData (Objective-c) 无法转换为整数 (Java)

NSUInteger written into NSData (Objective-c) cannot be converted as 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}

java字节数:{0, 1, 23, 84}

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

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

我尝试了很多答案,但我没有找到解决方案。

如何将我的字节数组转换为整数无论使用何种语言编写它

非常感谢您的帮助。

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

More information on Wikipedia

我决定将我的 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)