Reputation: 75
I'm working on my Web Server using Node JS and Express.js. I need to insert hex value in a Buffer, starting from a binary string. My code is something like this:
var buffer = fs.readFileSync("myBINfile.dat");
setValue(buffer, 4);
function setValue(buffer, i) {
var value1 = parseInt(buffer[i].toString(16), 16).toString(2).toString()
value1 = "0" + value1.substring(1, value1.length);
var hex = parseInt(value1, 2).toString(16);
console.log(hex); // print a8 (correct)
buffer[i] = hex;
console.log(buffer[i]); // print 0 (why?)
}
The buffer contains a hex file. value1
is read correctly. How can fix this this problem?
Thanks
Upvotes: 0
Views: 3560
Reputation: 7056
You're writing a string value into your Buffer
object rather than a numerical value that it expects. Replace the line:
var hex = parseInt(value1, 2).toString(16);
with:
var hex = parseInt(value1, 2);
"a8"
is really just the integer value 168 (you'll find if you console.log(value1)
before your var hex = parseInt(value1, 2).toString(16);
line, you'll get 10101000
(168 in binary)). When you write this value to the buffer, you really just want to write the integer value, not the string "a8"
.
The "hex value" as you put it, is actually just a number, hex is simply a presentation format. You don't store "hex numbers" or "binary numbers", you just store the numbers themselves.
As a result doing this you'll find console.log(hex);
outputs 168 instead and think "That's wrong though!", but it's not, because 168 is a8.
The reason why you'll find it works with some values but not others is because any values which result in a purely numerical hex value (e.g. "22"
or "67"
) will be automatically converted the their numerical equivalent (22
or 67
). In your case however "a8"
the value cannot be converted to the number type required by the buffer and so is discarded and 0
is written.
Upvotes: 2