0

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
Lewis
  • 11
  • 1
  • 1
    I may be wrong, but i think you will not be able to do this, considering an int is just a binary, 05 make no sense. I fear that you'll have to keep it as string. – Vollfeiw May 04 '21 at 11:47
  • Does this answer your question? [How to output numbers with leading zeros in JavaScript?](https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript) – Peter B May 04 '21 at 11:47
  • Does this answer your question? [Unable to retain leading zeros in javascript](https://stackoverflow.com/questions/25048708/unable-to-retain-leading-zeros-in-javascript) – Ivar May 04 '21 at 11:55
  • Ok great, looks like It'll have to be a string in that case. Thank you for your time! – Lewis May 04 '21 at 11:57

0 Answers0