ITeye博客

how to reverse bits in a byte?

standalone · 2012-07-03 17:59 · algorithm · 非技术 · Markdown

Given a 8-bit byte, assume its bits are b8b7...b1. Provide an algorithm to reverse the bit sequence. Result should be b1b2b3...b8.

An simple answer:

Suppose the byte is c.

c=((c>>1) & 0x55) | ((c<<1) & 0xAA)); // we got 78563412

c=((c>>2) & 0x33) | ((c<<2) & 0xCC)); // we got 56781234

c=((c>>4) | (c<<4)); // we got 12345678

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。