Reputation: 2632
I have (.hex) file that represent data in hexadicimal format. here are sample of the file:
:100080000C9408010C9408010C9408010C940801CC :100090000C9408010C9408010C9408010C9428019C :1000A0000C9408010C9408010C9408010C940801AC :1000B0000C9408010C9408010C9408010C9408019C :1000C0000C9408010C9408010C9408010C9408018C :1000D0000C9408010C9408010C9408010C9408017C
I write the following nodejs code to read the file and convert it to Buffer in the end to be sent using serial.
var fs = require("fs");
fs.readFile('./code.hex', function(err, code){
var str = code.toString();
var line = str.split('\n');
addr = line[1].slice(1, 9);
//addr_num = Number(addr, 'hex');
data = line[1].slice(9, (line[1].length - 3));
console.log(data);
var buf = new Buffer(data, 'hex');
}
The first 8 digits in the line are part of an address and the rest of the line is the data. What I want is to read the addr
as a number compare it with other variables using if
condition. When I tried addr_num = Number(addr, 'hex');
the result was NAN
. Is there a way to read it as a number?
Upvotes: 1
Views: 5162
Reputation: 8774
Use:
parseInt(addr, 16)
instead of:
Number(addr, 'hex')
to parse a string with radix 16 (hex) as a number.
There are a couple of differences between the two which you can read up on here and here, but essentially parseInt()
allows you to specify the radix whereas Number()
doesn't.
Both will try to guess the radix based on the format of the string to parse (if not specified), so in theory you could also do:
Number('0x' + addr)
or
parseInt('0x' + addr)
but since the string you're reading from the file isn't in this format and you'd have to stitch '0x'
in front of it, you're probably better off just using parseInt(addr, 16)
.
Upvotes: 2