字符串到长转换在C和Java上有所不同,为什么?

sam*_*m_k 1 c java byte long-integer

我有一个字符串喜欢"01030920316".当我要转换这个字符串时,然后转换为字节,然后给出下面的输出为java

output in java : Tag in bytes :  0, 0, 0, 0, 61, 114, -104, 124
Run Code Online (Sandbox Code Playgroud)

当我得到这个输出时,我在C中做同样的事情

output in C : Tag in bytes : 124,152,114,61,0,0,0,0
Run Code Online (Sandbox Code Playgroud)

在这里,我理解-104 and 152因为有符号和无符号之间的不同,但是为什么在java和C中最初为0.对于这种行为,当我的这个字节进入C程序端进行验证时,我遇到了问题.

请解释我发生问题的地方.

Java程序:

final byte[] tagBytes = ByteBuffer.allocate(8)
                .putLong(Long.parseLong("01030920316")).array();
System.out.println("Tag in bytes  >> " + Arrays.toString(tagBytes));
Run Code Online (Sandbox Code Playgroud)

C程序:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

/** To access long long values as a byte array*/
typedef union uInt64ToByte__
{
    uint64_t m_Value;
    unsigned char m_ByteArray[8];

}uInt64ToByte;

int main()
{
    uInt64ToByte longLongToByteArrayUnion;
    longLongToByteArrayUnion.m_Value = atoll("01030920316");
    printf("%d,%d,%d,%d,%d,%d,%d,%d",longLongToByteArrayUnion.m_ByteArray[0],longLongToByteArrayUnion.m_ByteArray[1],longLongToByteArrayUnion.m_ByteArray[2],longLongToByteArrayUnion.m_ByteArray[3],longLongToByteArrayUnion.m_ByteArray[4],longLongToByteArrayUnion.m_ByteArray[5],longLongToByteArrayUnion.m_ByteArray[6],longLongToByteArrayUnion.m_ByteArray[7]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 14

java中的输出:以字节为单位的标记:0,0,0,0,61,114,-104,124

默认情况下,Java的ByteBuffer是Big Endian,它的字节是有符号的,因此大于127的字节显示为负数.

C中的输出:以字节为单位的标记:124,152,114,61,0,0,0,0

C的数组使用本机字节endianess,它在x86/x64系统上是小端.在unsigned char将具有范围为0至255.

要用Java生成与C相同的输出,你可以做到

final byte[] tagBytes = ByteBuffer.allocate(8).order(ByteOrder.nativeOrder())
        .putLong(Long.parseLong("01030920316")).array();
int[] unsigned = new int[tagBytes.length];
for (int i = 0; i < tagBytes.length; i++)
    unsigned[i] = tagBytes[i] & 0xFF;
System.out.println("Tag in bytes  >> " + Arrays.toString(unsigned));
Run Code Online (Sandbox Code Playgroud)

版画

Tag in bytes  >> [124, 152, 114, 61, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)

  • C++中的格式取决于平台和实现.在C++中格式化以匹配Java格式可能更容易,因为你必须在C++中进行格式化; 没有标准的二进制输出格式. (2认同)