---
title: "how to reverse bits in a byte?"
author: "standalone"
date: "2012-07-03T17:59:44Z"
tags: []
categories: ["非技术"]
slug: "how-to-reverse-bits-in-a-byte"
draft: false
lastmod: "2012-07-03T17:59:44Z"
id: 1575941
url: "https://standalone.iteye.com/blog/1575941"
---

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