Int 到字节数组和返回不会在大数字上给出相同的值

Int to byte array and back doesnt give the same value on big numbers

本文关键字:数字上 数组 到字节 返回 Int      更新时间:2023-10-16

我正在尝试将整数转换为字节数组,然后执行base64为Azure Rest API创建blockId。我的第一位是正确的,当我将 int 转换为 base64 字符串时:

int a = 127;
int b = 4000;

C#:

byte[] blockIdBytes = BitConverter.GetBytes(a);
string blockIdBase64 = Convert.ToBase64String(blockIdBytes);

a给出"fwAAAA==",b给出"oA8AAA=="

C++

QByteArray temp;
for(int i = 0; i < sizeof(a); i++) {
    temp.append((char)(a >> (i * 8)));
}

a给出"fwAAAA==",b给出"oA8AAA=="(与上面的值相同,这是正确的)

现在的问题是,当我尝试将 base64 字符串转换回 int 时?我的字节数组到 int 方法不适用于大于 127 的数字,为什么?

int result = 0;
for(int i = temp.size(); i >= 0; i--) {
    result = (result << 8) + temp[i];
}

127 有效,但当我做 128(例如)时,结果是"-128"。我意识到它溢出了,但为什么以及在哪里?

编辑:

试:

QByteArray temp;
int a = 340;
for(int i = 0; i < sizeof(a); i++) {
  temp.append((unsigned char)(a >> (i * 8)));
}

当我转换回来时,它实际上给出了"340","255"给出了"-1","256"给出了"256"

当你转换

回来时,你需要将temp[i]中的所有值视为unsigned char 或忽略有符号位 。在下面的代码片段中,您最终将 temp[i] 提升为整数,然后明确地将有符号位重置为 0,使其为正

result = (result << 8) + ((int)(temp[i]) & 0xFF)

您应该能够使用

result = (result << 8) + ((unsigned char)(temp[i]))