我正在尝试将 int 转换为字节数组,然后执行 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 时?我的 bytearray to 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]))
关于c# - Int 到字节数组并返回不给大数字相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291871/