Rotates 8 bits

For questions and comments on programming in general. And for any items that don't fit into the forums below.

Moderators: Benj, Mods

Post Reply
samtin
Posts: 12
Joined: Fri Jun 24, 2016 8:14 pm
Has thanked: 1 time
Been thanked: 1 time
Contact:

Rotates 8 bits

Post by samtin »

Hi,

How do I rotate 8 bits to the right or to the left by 1 bit?

1011 1110
0111 1101

Thank you!

mnf
Valued Contributor
Valued Contributor
Posts: 1200
Joined: Wed May 31, 2017 11:57 am
Has thanked: 70 times
Been thanked: 440 times
Contact:

Re: Rotates 8 bits

Post by mnf »

You need to shift and then add the shifted 'out' bit back in.

so assuming 8 bit values (.x and .msb and .lsb)

.msb = .x & 0x80
.x = (.x << 1) | (.msb != 0) // Or use (.msb >> 7) not sure which is quicker?

Will do a left rotate - note you could probably cram it into one line and do without the extra variable)

.lsb = .x & 1
.x = (.x >> 1) | (.lsb << 7)

Will rotate 'right'

Martin

samtin
Posts: 12
Joined: Fri Jun 24, 2016 8:14 pm
Has thanked: 1 time
Been thanked: 1 time
Contact:

Re: Rotates 8 bits

Post by samtin »

Hi Martin,

Thank you very much for the answer. :D

All the best!

Post Reply