Int 到字节数组和返回不会在大数字上给出相同的值
Int to byte array and back doesnt give the same value on big numbers
我正在尝试将整数转换为字节数组,然后执行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]))
相关文章:
- 如何将较大数字中从0到9的单个数字放入只包含数字的数组中
- c++ 中堆上数组的默认值是多少?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- C++ 将数字输入数组并输出
- 将大数字乘以数组C
- 如何计算一个数字在数组中出现的次数
- 打印每行包含 n 个数字的数组
- 将2位数字的数组转换为整数(C++)
- 将数字动态数组设置为数组或容器 c++
- 如何生成包含 256 个不同数字的数组
- 将数字从数组中的文件放在行中
- C++上数组错误的大小
- C++:运行程序时出现分段错误(将文件中的数字输入数组)
- 是否可以将两个数字放在数组的一个单元格中
- 查找总和除以给定数字的数组的子数组的数量
- C++ - 如何将空格分隔的数字输入数组
- C++ 对输出不同数字的数组进行气泡排序
- 在 100 个数字的数组中查找 5 个最高数字的总和
- 数字在数组中重复的次数,C++
- 在Rcpp中分配一个大型的二维数字向量数组