# Bitwise manipulation: reversing bit order

Oh poo - I coded myself into a painted corner! LOL

is there an easy way to reverse bit order in a variable?
That is:
1100 → 0011
0100 → 0010
etc

I figure I could just set up 2 local variables as counters, have one count down, one count up, and go bit by bit comparing the original counting up each bit position and flipping the bits on a destination variable counting down each bit position.

Been searching online for maybe some majiks, but everything seems to end up on a C++ tutorial page using functions we don’t have access to.

Yes, not easy,

The logic you outlines makes sense to me, however I’m not sure why you would ever want to do this. I’ve never encountered a use case for this type of bit manipulation.

Steve Caldwell
Bome Customer Care

Also available for paid consulting services: bome@sniz.biz

This should work but always be very careful when using loops in rules that you don’t create an infinite loop and lock up MT Pro

``````ga=124
// reverse bits in ga and put back in ga
rr=0

pp=0
tt=31-pp
Label "Loop"

// get bit
ss=ga>>pp
ss=ss&1
uu=ss<<tt
rr=rr|uu
pp=pp+1
tt=31-pp
if pp<32 then goto "Loop"
// done , put it in ga

ga=rr

``````

Steve Caldwell
Bome Customer Care

Also available for paid consulting services: bome@sniz.biz

thanks Steve!

I just popped back on here to share what I came up with. Excellent! Thank you!

Yes, I do weird things, but this is because I didn’t know where I was going when I started coding this section, and let’s say buttons that I relate to on my side as 1 → 4 are, under the hood, bits 4 → 1.
So, I either flip the bit order or rewrite stuff I wrote a long time ago which will take me weeks to figure out what I did. LOL

Yes, I get it. I’ve painted (coded) myself into a corner more than once as well.

Steve Caldwell
Bome Customer Care

Also available for paid consulting services: bome@sniz.biz