mr_sol
mr_sol

Reputation: 241

Bitmanipulation

I need a javascript-function which convert a 4 Byte HEX String to BIN(use a Part auf the Bytes) to DEC

These data come from a sensor and the measured values are distributed in this string.

example ("ff027608", BitOffset=7,BitSize=4)

11111111000000100111011000001000 -> 1000 -> 8 (DEC)

-----------^^^^

Starting at Offset 7 is a 4 Bit Value

function convert(bp,BitOffset,BitSize){
  bp >>= parseFloat(BitOffset);
  bp <<= parseFloat(BitSize);
  return bp;
}; 

1) How do I convert Hex to Long Integer

2) How to cut out the 4-byte value ICHD

3) How do I convert it to a DEC

Or is there a better way

Thank you in advance

Upvotes: 1

Views: 140

Answers (2)

Krzysztof
Krzysztof

Reputation: 16150

I think this is easier way:

function convert(input, offset, size){
    var result = input.substr(offset, size);
    result = parseInt(result, 2);

    return result;
}

You can convert hex to in using parseInt(hex, 16), but I'm affraid JS doesn't support longs (AFAIK). If you need long, probably you must split it into two ints.

Upvotes: 0

noob
noob

Reputation: 9212

You can convert from hex do dec with:

var dec = parseInt(hex, 16);

and from dec to hex with

var hex = dec.toString(16);

and from bin to dec with

var dec = parseInt(bin, 2);

and from dec to bin with

var bin = dec.toString(2);

Upvotes: 1

Related Questions