Search code examples
rubycomputer-science

Least significant bit first


While working on ruby I came across:

> "cc".unpack('b8B8')
 => ["11000110", "01100011"] 

Then I tried Googleing to find a good answer on "least significant bit", but could not find any.

Anyone care to explain, or point me in the right direction where I can understand the difference between "LSB first" and "MSB first".


Solution

  • It has to do with the direction of the bits. Notice that in this example it's unpacking two ascii "c" characters, and yet the bits are mirror images of each other. LSB means the rightmost (least-significant) bit is the first bit. MSB means the leftmost (most-significant) is the first bit.

    As a simple example, consider the number 5, which in "normal" (readable) binary looks like this:

    00000101
    

    The least significant bit is the rightmost 1, because that is the 2^0 position (or just plan 1). It doesn't impact the value too much. The one next to it is the 2^1 position (or just plain 0 in this case), which is a bit more significant. The bit to its left (2^2 or just plain 4) is more significant still. So we say this is MSB notation because the most significant bit (2^7) comes first. If we change it to LSB, it simply becomes:

    10100000
    

    Easy right?

    (And yes, for all you hardware gurus out there I'm aware that this changes from one architecture to another depending on endianness, but this is a simple answer for a simple question)