0

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

3
  • "Hex Buffer and i are previusly defined and they are valid." - Can you show that? because otherwise, this code is fine, and testing it works as expected. Commented Aug 31, 2021 at 12:27
  • And you're sure this is your latest code? (note your comment says // print a8 (correct), but this can't print a8 as value1 = "0" + value1.substring(1, value1.length); prefixes whatever value would be in there with a 0) Commented Aug 31, 2021 at 13:09
  • I was wrong to update. It seems a simple operation but something is not working Commented Aug 31, 2021 at 13:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.