I’m trying to convert an int to an byte array and then do base64 to create a blockId for Azure Rest API. I’ve gotten the first bit correct, the when where I convert the int to a base64 string:
int a = 127;
int b = 4000;
C#:
byte[] blockIdBytes = BitConverter.GetBytes(a);
string blockIdBase64 = Convert.ToBase64String(blockIdBytes);
a gives “fwAAAA==” and b gives “oA8AAA==”
C++
QByteArray temp;
for(int i = 0; i < sizeof(a); i++) {
temp.append((char)(a >> (i * 8)));
}
a gives “fwAAAA==” and b gives “oA8AAA==” (same values as above, which is correct)
Now the issue is, when I try to convert the base64-string back to an int? My bytearray to int method does not work on numbers bigger than 127, why?
int result = 0;
for(int i = temp.size(); i >= 0; i--) {
result = (result << 8) + temp[i];
}
127 works but when I do 128 (for example) the result is “-128”. I realize the it overflows, but why and where?
EDIT:
Tried:
QByteArray temp;
int a = 340;
for(int i = 0; i < sizeof(a); i++) {
temp.append((unsigned char)(a >> (i * 8)));
}
Which actaully gives “340” when I convert it back, “255” gives “-1” and “256” gives “256”
when you are converting back you need to treat all the values in temp[i] as
unsigned charor ignore the signed bit . In the below code snippet you end up promoting temp[i] to integer then explicitly we reset the signed bit if any to 0 making it positive
result = (result << 8) + ((int)(temp[i]) & 0xFF)you should be able to achieve the same using
result = (result << 8) + ((unsigned char)(temp[i]))