deepseadiving
deepseadiving

Reputation: 763

Converting hex string 2 chars at a time

I'm reading through some JavaScript code that parses a hex string into a buffer, like so:

function bufferFromHexString(string)
{
    var buffer = new Buffer(string.length/2);

    for (var i=0; i<string.length/2; i++)
    {
        buffer.writeInt8( parseInt(input.substr(i*2,2), 16), i );
    }

    return buffer;
}

But I'm not sure why this is taking two characters at a time, rather than one. Can anyone explain this?

Upvotes: 0

Views: 100

Answers (2)

maerics
maerics

Reputation: 156622

One byte (eight bits) has 2^8=256 possible values.

To represent 256 in hexadecimal you need two digits (e.g. 0xff = 255d).

00 = 0
01 = 1
02 = 2
...
fd = 253
fe = 254
ff = 255

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

It takes two hex characters to make an eight-bit (one-byte) integer. That's all there is to it.

Upvotes: 1

Related Questions