Convert binary bit-field from big endian to little endian


I have a product that is actually written in Ruby (currently 2.4).

However, I have discovered there is a preference to endian-ness.
When the bit offset is non-zero I have a limitation that only big endian
is allowed.

I have figured out if I were to reverse the bits, I could achieve a
little endian for my case.

I have a bit field 11 bits long with a bit offset of 3 (in the middle) and I
need these bits reversed.

I have googled and found a few different methods with different results
doing different things. Not what I need.

This data is part of a larger record that is transmitted via RF. So it is a
bit different than other topics I have read.

Any suggestions?


I think I answered my own question. Try the ruby interpreter (2.4.0) I was able to

For a given decimal number say 65 do

65.to_s(2).reverse # => ‘1000001’

Then I realized this is a fixed 11-bit field. Plus I need the output as decimal.
Plus I’m doing as a simple command not a function to call.

Can that be done?


I haven’t figured out how to do this in a single command. I was able to the
following in 4 lines though.

Let i be the number value to represent the bit field to reverse, and w be the number of bits as input.

l = i.length
x = i << (w - l)

This turned out to be a good lesson for me learning Ruby!