We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I'm reading data from a text file and want two join to bytes together and read the value as an INT.
So the first byte I read is
0x02
and the 2nd byte I read is
0x58
I would like to convert 0x0258 into an int which would be 600
If I just add them together it doesn't work out because it is simply adding the digits together instead of making a longer digit. I hope this makes some kind of sense.
Here is what I have,
byte b1 = b[15];
byte b2 = b[16];
println (hex(b1));
println (hex(b2));
numPixels = byte(b1) + byte(b2);
println(numPixels);
I'm sure it's pretty simple but searching the web isn't getting me very far.
Thanks.
Phil
Answers
Here's one way. I'm sure you could do it with addition and bitshift operators (
<<
) too, but this is the most clear to me.That worked great, thanks
Phil
Another easy way:
https://processing.org/reference/leftshift.html
Kf
Excellent, thanks.
Phil
Like kfrajer's but will also work for negative bytes.
Actually I get different results if I use the reply from kfrajer.
Here is my code with the results from each method.
I have a solution but curious what the difference is.
Thanks.
Phil
The difference happens because of negative bytes. For example -1 is 0xff as a byte but 0xffffffff as an int.
So it you want -1 + -1 to be 0xffff, then you have to mask it.
The + operator should work the same as the | operator as the masks don't overlap, but I switched to | just to be sure.