I have a byte stream being read from a TCP socket in Node.JS and I'm parsing the packets in byte order. One of the fields I'm looking for is battery voltage from a hardware device- and this battery voltage can start with a zero.
Running a parseInt()
on the data works fine- until there's a leading zero. This appears to be by design, and in looking it up one suggestion involved specifying the radix as 10. This did not appear to solve the problem.
Here's an example of a packet which I'm parsing:
const testData = [0x33, 0x39, 0x33, 0x35, 0x32, 0x30, 0x46, 0x41, 0x42, 0x42, 0x30, 0x45, 0x39, 0x30, 0x45, 0x45, 0x31, 0x32, 0x33, 0x34, 0x30];
In ASCII, this equates to:
3935 | 20FABB0E90EE | 1234 | 0
If you run a parseInt() on the two integer fields, they work fine. But, if we change it so that one of the fields (the first 4 bytes in this case, for brevity) start with a zero:
const testData = [0x30, 0x39, 0x33, 0x35, 0x32, 0x30, 0x46, 0x41, 0x42, 0x42, 0x30, 0x45, 0x39, 0x30, 0x45, 0x45, 0x31, 0x32, 0x33, 0x34, 0x30];
So, in ascii, the first 4 bytes works out as: 0935, when we: parseInt(0935)
, the leading zero is completely truncated. Is there any way to prevent this behaviour, or am I just gonna have to use a string? (not ideal!).
Furthermore, console.log seems to irradiate this same behaviour. For example:
> let example = 0935;
> console.log(example);
935
> parseInt(example);
935
> let example2 = "0935";
> console.log(example2);
0935
> parseInt(example2);
935