1

I am trying to examine the binary data given a Buffer like so:

<Buffer 08 30 66 6d 41 64 69 76 66>

TMK that is 8 bytes of data.

What I am looking to do is examine the first byte, and look at the most significant bit (leftmost bit) in that first byte.

How can I find out if that first bit is a zero or one?

1 Answer 1

3

The simplest solution is this:

Number(buf[0] > 127)

Works because:

  1. JS treats bytes as unsigned, AKA always positive; a byte's value is thus in the range [0..255], as opposed to [-128..127] for signed bytes.
  2. Number(true) == 1, Number(false) == 0
  3. the most significant bit is 1 only when byte is in range [128..255]

(Bonus) A harder to read but sexier version:

((buf[0] & 0xff) >> 7)
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.