how to reverse the bits using bit wise operators in c language
Eg:
i/p: 10010101
o/p: 10101001
If it's just 8 bits:
u_char in = 0x95;
u_char out = 0;
for (int i = 0; i < 8; ++i) {
out <<= 1;
out |= (in & 0x01);
in >>= 1;
}
Or for bonus points:
u_char in = 0x95;
u_char out = in;
out = (out & 0xaa) >> 1 | (out & 0x55) << 1;
out = (out & 0xcc) >> 2 | (out & 0x33) << 2;
out = (out & 0xf0) >> 4 | (out & 0x0f) << 4;
figuring out how the last one works is an exercise for the reader ;-)
Knuth has a section on Bit reversal in The Art of Computer Programming Vol 4A, bitwise tricks and techniques.
To reverse the bits of a 32 bit number in a divide and conquer fashion he uses magic constants
u0= 1010101010101010, (from -1/(2+1)
u1= 0011001100110011, (from -1/(4+1)
u2= 0000111100001111, (from -1/(16+1)
u3= 0000000011111111, (from -1/(256+1)
Method credited to Henry Warren Jr., Hackers delight.
unsigned int u0 = 0x55555555;
x = (((x >> 1) & u0) | ((x & u0) << 1));
unsigned int u1 = 0x33333333;
x = (((x >> 2) & u1) | ((x & u1) << 2));
unsigned int u2 = 0x0f0f0f0f;
x = (((x >> 4) & u2) | ((x & u2) << 4));
unsigned int u3 = 0x00ff00ff;
x = (((x >> 8) & u3) | ((x & u3) << 8));
x = ((x >> 16) | (x << 16) mod 0x100000000); // reversed
The 16 and 8 bit cases are left as an exercise to the reader.
Well, this might not be the most elegant solution but it is a solution:
int reverseBits(int x) {
int res = 0;
int len = sizeof(x) * 8; // no of bits to reverse
int i, shift, mask;
for(i = 0; i < len; i++) {
mask = 1 << i; //which bit we are at
shift = len - 2*i - 1;
mask &= x;
mask = (shift > 0) ? mask << shift : mask >> -shift;
res |= mask; // mask the bit we work at at shift it to the left
}
return res;
}
Tested it on a sheet of paper and it seemed to work :D
Edit: Yeah, this is indeed very complicated. I dunno why, but I wanted to find a solution without touching the input, so this came to my haead
Related
Suppose I have two 4-bit values, ABCD and abcd. How to interleave it, so it becomes AaBbCcDd, using bitwise operators? Example in pseudo-C:
nibble a = 0b1001;
nibble b = 0b1100;
char c = foo(a,b);
print_bits(c);
// output: 0b11010010
Note: 4 bits is just for illustration, I want to do this with two 32bit ints.
This is called the perfect shuffle operation, and it's discussed at length in the Bible Of Bit Bashing, Hacker's Delight by Henry Warren, section 7-2 "Shuffling Bits."
Assuming x is a 32-bit integer with a in its high-order 16 bits and b in its low-order 16 bits:
unsigned int x = (a << 16) | b; /* put a and b in place */
the following straightforward C-like code accomplishes the perfect shuffle:
x = (x & 0x0000FF00) << 8 | (x >> 8) & 0x0000FF00 | x & 0xFF0000FF;
x = (x & 0x00F000F0) << 4 | (x >> 4) & 0x00F000F0 | x & 0xF00FF00F;
x = (x & 0x0C0C0C0C) << 2 | (x >> 2) & 0x0C0C0C0C | x & 0xC3C3C3C3;
x = (x & 0x22222222) << 1 | (x >> 1) & 0x22222222 | x & 0x99999999;
He also gives an alternative form which is faster on some CPUs, and (I think) a little more clear and extensible:
unsigned int t; /* an intermediate, temporary variable */
t = (x ^ (x >> 8)) & 0x0000FF00; x = x ^ t ^ (t << 8);
t = (x ^ (x >> 4)) & 0x00F000F0; x = x ^ t ^ (t << 4);
t = (x ^ (x >> 2)) & 0x0C0C0C0C; x = x ^ t ^ (t << 2);
t = (x ^ (x >> 1)) & 0x22222222; x = x ^ t ^ (t << 1);
I see you have edited your question to ask for a 64-bit result from two 32-bit inputs. I'd have to think about how to extend Warren's technique. I think it wouldn't be too hard, but I'd have to give it some thought. If someone else wanted to start here and give a 64-bit version, I'd be happy to upvote them.
EDITED FOR 64 BITS
I extended the second solution to 64 bits in a straightforward way. First I doubled the length of each of the constants. Then I added a line at the beginning to swap adjacent double-bytes and intermix them. In the following 4 lines, which are pretty much the same as the 32-bit version, the first line swaps adjacent bytes and intermixes, the second line drops down to nibbles, the third line to double-bits, and the last line to single bits.
unsigned long long int t; /* an intermediate, temporary variable */
t = (x ^ (x >> 16)) & 0x00000000FFFF0000ull; x = x ^ t ^ (t << 16);
t = (x ^ (x >> 8)) & 0x0000FF000000FF00ull; x = x ^ t ^ (t << 8);
t = (x ^ (x >> 4)) & 0x00F000F000F000F0ull; x = x ^ t ^ (t << 4);
t = (x ^ (x >> 2)) & 0x0C0C0C0C0C0C0C0Cull; x = x ^ t ^ (t << 2);
t = (x ^ (x >> 1)) & 0x2222222222222222ull; x = x ^ t ^ (t << 1);
From Stanford "Bit Twiddling Hacks" page:
https://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableObvious
uint32_t x = /*...*/, y = /*...*/;
uint64_t z = 0;
for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed...
{
z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);
}
Look at the page they propose different and faster algorithms to achieve the same.
Like so:
#include <limits.h>
typedef unsigned int half;
typedef unsigned long long full;
full mix_bits(half a,half b)
{
full result = 0;
for (int i=0; i<sizeof(half)*CHAR_BIT; i++)
result |= (((a>>i)&1)<<(2*i+1))|(((b>>i)&1)<<(2*i+0));
return result;
}
Here is a loop-based solution that is hopefully more readable than some of the others already here.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
uint64_t interleave(uint32_t a, uint32_t b) {
uint64_t result = 0;
int i;
for (i = 0; i < 31; i++) {
result |= (a >> (31 - i)) & 1;
result <<= 1;
result |= (b >> (31 - i)) & 1;
result <<= 1;
}
// Skip the last left shift.
result |= (a >> (31 - i)) & 1;
result <<= 1;
result |= (b >> (31 - i)) & 1;
return result;
}
void printBits(uint64_t a) {
int i;
for (i = 0; i < 64; i++)
printf("%lu", (a >> (63 - i)) & 1);
puts("");
}
int main(){
uint32_t a = 0x9;
uint32_t b = 0x6;
uint64_t c = interleave(a,b);
printBits(a);
printBits(b);
printBits(c);
}
I have used the 2 tricks/operations used in this post How do you set, clear, and toggle a single bit? of setting a bit at particular index and checking the bit at particular index.
The following code is implemented using these 2 operations only.
int a = 0b1001;
int b = 0b1100;
long int c=0;
int index; //To specify index of c
int bit,i;
//Set bits in c from right to left.
for(i=32;i>=0;i--)
{
index=2*i+1; //We have to add the bit in c at this index
//Check a
bit=a&(1<<i); //Checking whether the i-th bit is set in a
if(bit)
c|=1<<index; //Setting bit in c at index
index--;
//Check b
bit=b&(1<<i); //Checking whether the i-th bit is set in b
if(bit)
c|=1<<index; //Setting bit in c at index
}
printf("%ld",c);
Output: 210 which is 0b11010010
I want reverse the binary
unsigned short gf_t = 44 // = 00101100
in 00110100 in C language. How i will able to for that using bitwise operators?
pdta: My computer have 32 bits pattern.
When in doubt, see the Bit Twiddling Hacks page. In fact, there you can find a very simple algorithm that does what you want...
Reverse bits the obvious way
unsigned int v; // input bits to be reversed
unsigned int r = v; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1)
{
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
On October 15, 2004, Michael Hoisie pointed out a bug in the original version. Randal E. Bryant suggested removing an extra operation on May 3, 2005. Behdad Esfabod suggested a slight change that eliminated one iteration of the loop on May 18, 2005. Then, on February 6, 2007, Liyong Zhou suggested a better version that loops while v is not 0, so rather than iterating over all bits it stops early.
There is also, however, several nifty approaches documented there. You can look into those and try to understand them for learning :-) For example, here is one particular interesting form...
Reverse an N-bit quantity in parallel in 5 * lg(N) operations:
unsigned int v; // 32-bit word to reverse bit order
// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16 ) | ( v << 16);
Note that if sizeof(unsigned short) * CHAR_BIT is 16, the appropriate usage would only require the first 4 transpositions -- see as follows:
unsigned short v;
// swap odd and even bits
v = ((v >> 1) & 0x5555) | ((v & 0x5555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x3333) | ((v & 0x3333) << 2);
// swap nibbles ...
v = ((v >> 4) & 0x0F0F) | ((v & 0x0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF) | ((v & 0x00FF) << 8);
That being said, why not just use uint16_t (if it's available)?
Here is working example (see ideone):
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
inline uint16_t reverse(uint16_t v) {
v = ((v >> 1) & 0x5555) | ((v & 0x5555) << 1); /* swap odd/even bits */
v = ((v >> 2) & 0x3333) | ((v & 0x3333) << 2); /* swap bit pairs */
v = ((v >> 4) & 0x0F0F) | ((v & 0x0F0F) << 4); /* swap nibbles */
v = ((v >> 8) & 0x00FF) | ((v & 0x00FF) << 8); /* swap bytes */
return v;
}
main() {
uint16_t gf_t = 44;
printf("%hu\n", reverse(gf_t));
}
You can do it like this (v is a 16-bit number):
v = ((v >> 1) & 0x5555) | ((v & 0x5555) << 1);
v = ((v >> 2) & 0x3333) | ((v & 0x3333) << 2);
v = ((v >> 4) & 0x0F0F) | ((v & 0x0F0F) << 4);
v = ((v >> 8) & 0x00FF) | ((v & 0x00FF) << 8);
The first line swaps the odd and even bits
The second line swaps consecutive pairs
The third line swaps groups of four bits
The last line swaps the two bytes
You can find more tricks like this here. Here is a link to ideone with this code snippet.
If you are trying to make sense of this, write binary representations of the "magic numbers" used in the example:
0x5555 is 0101010101010101
0x3333 is 0011001100110011
0x0F0F is 0000111100001111
0x00FF is 0000000011111111
The & operation clears out the "unwanted" bits; the shifts reposition the desired parts over the "zero gaps" opened up by the masking operation, and finally the | re-combines the two parts.
Normally you and the input with 1 to get its LSB. Or that into the result. Shift the result left a bit and the input right a bit. Repeat for a total of 32 iterations.
The binary is 0000000000101100 - There are 16 bits in a short.
// includes go here
int main() {
unsigned short gf_t = 44;
cout << hex << gf_t << endl;
unsigned short gf_r = 0;
for ( int iter = 0; iter < sizeof(short) * 8; ++iter )
{
unsigned short tmp = gf_t;
tmp = tmp & 1;
gf_r = (gf_r << 1 ) | tmp;
gf_t = gf_t >> 1;
}
cout << hex << gf_r << endl;
}
Like this:
input: 10010011
(10->01->00->11)
output: 11000110
(11->00->01->10)
input: 11010001
(11->01->00->01)
output: 01000111
(01->00->01->11)
Anyone has any ideas about that?
Fewer operations than lserni's algorithm:
uint32_t reverseByTwo(uint32_t value) {
value = ((value & 0x03030303) << 2) | ((value >> 2) & 0x03030303); // swap adjacent pairs
value = ((value & 0x0F0F0F0F) << 4) | ((value >> 4) & 0x0F0F0F0F); // swap nibbles
value = ((value & 0x00FF00FF) << 8) | ((value >> 8) & 0x00FF00FF); // swap bytes
value = ((value & 0x0000FFFF) << 16) | ((value >> 16) & 0x0000FFFF);
return value;
}
For 64-bit values just add another swap for the 32-bit halves, for smaller types, just leave out the last few swaps.
Weird request. I'd do it like this:
uint32_t reverseByTwo(uint32_t value)
{
int i;
uint32_t new_value = 0;
for (i = 0; i < 16; i++)
{
new_value <<= 2;
new_value |= (value & 0x3);
value >>= 2;
}
return new_value;
}
At each iteration, the two LSB of value are placed in the two LSB of new_value, which is shifted to the left.
For an eight-bit value,
uint8_t reverseByTwo(uint8_t value)
{
int i;
uint32_t new_value = 0;
for (i = 0; i < 4; i++)
{
new_value <<= 2;
new_value |= (value & 0x3);
value >>= 2;
}
return new_value;
}
if performances are at a premium, you can manually unroll the loop (GCC should do this by itself, but sometimes doesn't bother) and declare the function as inline.
new_value = 0;
// new_value <<= 2; // First time not necessary
new_value |= (value & 0x3);
value >>= 2;
new_value <<= 2;
new_value |= (value & 0x3);
value >>= 2;
new_value <<= 2;
new_value |= (value & 0x3);
value >>= 2;
new_value <<= 2;
new_value |= (value & 0x3);
// value >>= 2;
return new_value;
The fastest possible way to transform the bits in a single byte (char) into another single byte is to build yourself an array:
unsigned char rev[256];
rev[0] = 0; /* 00000000 -> 00000000 */
...
rev[147] = 198; /* 10010011 -> 11000110 */
...
rev[198] = 147; /* 11000110 -> 10010011 */
...
rev[255] = 255; /* 11111111 -> 11111111 */
To convert a number x to its bit-reversed form, just write rev[x]. If you have multiple bytes to convert, such as in a 4-byte int, just look up the 4 bytes in the rev table.
You'll need to convert binary to another base (here, I use decimal) when writing this code, because C doesn't have binary constants (which would be ten times more useful than octal constants).
You could also put the values into the initializer, but you'll have to count positions to make sure everything is in the right place. (Maybe write a little program to do it!)
unsigned char rev[256] = {0, ..., 198, ..., 147, ..., 255};
Fill in the ... with all the other numbers in the right places.
$x = (($x & 0x33333333) << 2) | (($x & 0xCCCCCCCC) >> 2);
$x = (($x & 0x0F0F0F0F) << 4) | (($x & 0xFOFOFOFO) >> 4);
$x = (($x & 0x00FF00FF) << 8) | (($x & 0xFF00FF00) >> 8);
$x = (($x & 0x0000FFFF) << 16) | (($x & 0xFFFF0000) >> 16);
To give credit where due, this algorithm came from "Hacker's Delight" by Henry S. Warren, Jr. The only difference is that the algorithm in the book didn't reverse by pairs; it just reversed the bits.
#include <limits.h>
#define INT_BITS (sizeof(int) * CHAR_BIT)
unsigned reverse_bits(unsigned x) {
#define PAIR(i) ((((x) >> (i*2)) & 3) << (INT_BITS - (i+1)*2))
unsigned result = 0;
unsigned i;
for(i = 0; i < INT_BITS/2; i++) {
result |= PAIR(i);
}
return result;
}
Though this will do it for an unsigned int, whereas you might want to replace int and unsigned there with char and unsigned char.
If you want the fastest possible:
output =
((input & 0xc0) >> 6) |
((input & 0x30) >> 2) |
((input & 0xc) << 2) |
((input & 0x3) << 6);
You have bits (ab cd ef gh) and want (gh ef cd ab)
If you multiply by 0x101 and store in 16 bit int, you get (ab cd ef gh ab cd ef gh).
Then you have your bit pattern in that number in two group of four bits:
(00 00 ef 00 ab 00 00 00),
(00 00 00 gh 00 cd 00 00)
So you just have to shift and mask appropriately
unsigned char swap_bit_pairs(unsigned char b)
{
unsigned int a = 0x101*b;
return ((a >> 6) & 0x33) | ((a >> 2) & 0xCC);
}
So it's possible in 6 operations
EDIT: oups! I wrote 0x66 instead of 0xCC
I need to write an expression of one byte Hamming weight in terms of binary operations only (&, ^, >>); without any loop, just a formula.
I know that there are plenty algorithms, that allow computing Hamming weight, but all of them use arithmetical operations or looping.
If we take an algorithm from http://en.wikipedia.org/wiki/Hamming_weight, then the first sum D=B+C can be written as D = B^C^(B&C << 1), but two following sums are more complicated.
Does anyone have a hint?
UPDATE:
Thank you for help guys. Actually, I needed something like following:
int popcount_1(unsigned char in){
unsigned char m1 = 0x55;
unsigned char m2 = 0x33;
unsigned char m4 = 0x0f;
unsigned char B,C = 0;
unsigned char x = in;
x = (x & (x << 1) & (m1 << 1)) | (m1 & (x ^ (x >> 1)));
B = x & m2;
C = (x >> 2) & m2;
x = B ^ C ^ ((B & C) << 1);
B = (x & m4 ) ^ ((x >> 4) & m4);
C = (x & ((x >> 4) & m4)) << 1;
x = B ^ C ^ ((B & C) << 1);
return x;
}
This code will result in Hamming weight of variable in. It does not contain any +, -, or comparison instructions and it can work on 8bits microcontrollers.
Nevertheless, it takes more operations than most of other solutions. Now, I am trying to simplify it.
UPDATE2: Another solution, based on 64 bits registers, is proposed by #Evgeny Kluev
I think the best you can do is O(log n). Here is code (in Go) for the pop-count of a 32-bit integer. Extending this to 64-bits should be obvious if you need it, hopefully the comments make it clear what is actually going on:
func popCount(n uint32) int {
// each bit in n is a one-bit integer that indicates how many bits are set
// in that bit.
n = ((n & 0xAAAAAAAA) >> 1) + (n & 0x55555555)
// Now every two bits are a two bit integer that indicate how many bits were
// set in those two bits in the original number
n = ((n & 0xCCCCCCCC) >> 2) + (n & 0x33333333)
// Now we're at 4 bits
n = ((n & 0xF0F0F0F0) >> 4) + (n & 0x0F0F0F0F)
// 8 bits
n = ((n & 0xFF00FF00) >> 8) + (n & 0x00FF00FF)
// 16 bits
n = ((n & 0xFFFF0000) >> 16) + (n & 0x0000FFFF)
// kaboom - 32 bits
return int(n)
}
I'm not sure if this is what you search for, but here is just a formula using only shifts and bitwise and:
int weight(unsigned char x)
{
return ((0x876543210 >>
(((0x4332322132212110 >> ((x & 0xF) << 2)) & 0xF) << 2)) >>
((0x4332322132212110 >> (((x & 0xF0) >> 2)) & 0xF) << 2))
& 0xf;
}
Here shift operation is twice used as a substitute for array indexing (to find 4-bit hamming weights). And one more shift operation uses array indexing to perform addition.
the data type is char, and the pattern is follow:
source byte: [0][1][2][3][4][5][6][7]
destination: [6][7][4][5][2][3][0][1]
for example, if I pass a char, 29 to this function, it will do the swapping and return a char type value, which is 116.
How can I do the swapping?
thank you.
========================
Just wondering if I can do in this way?
unsigned char mask = 128;
char num = 0, value1 = 29;
int i, a;
for(i = 0; i < 8; i++) {
if (i == 0 || i == 1 || i == 6 || i == 7)
a = 6;
else
a = 2;
if(i < 4)
num = ((value1 & mask) >> a);
else
num = ((value1 & mask) << a);
result = (result | num);
if(i<7)
mask = mask >> 1;
}
I usually number my bits the other way -- so that bit 0 is the LSB. Following your numbering scheme:
unsigned char src = 29;
unsigned char dst = 0;
dst = (((src & 0x80) >> 6) | // bit 0
((src & 0x40) >> 6) | // bit 1
((src & 0x20) >> 2) | // bit 2
((src & 0x10) >> 2) | // bit 3
((src & 0x08) << 2) | // bit 4
((src & 0x04) << 2) | // bit 5
((src & 0x02) << 6) | // bit 6
((src & 0x01) << 6) // bit 7
);
Unless of course, you're numbering them "the right way", but drawing them "backwards" -- then just reverse what I've done above. (Not that I'm trying to start a religious war here...)
or a lookup table
just in case you dont understand that. Here is more detail
For each of the 256 possible inputs work out the answer (by hand)
then do
unsigned char answers[256] = {0x00, 0x40,0x21.....};
unsigned char answer = answers[input];
I hasten to add that the values I gave are an example - and are certainly not correct
See the "Reversing bit sequences" section on Bit Twiddling Hacks.
Also, if you want to do it yourself:
To read the n-th bit: int bit = value & (1 << n); If the bit is not set, bit is 0.
To set the n-th bit: value |= 1 << n; (value = value OR (1 shifted by n digits))
To clear the n-th bit: value &= ~(1 << n); (value = value AND NOT (1 shifted by n digits))
First swap the lower four bits with the higher four bits, then swap all adjacent pairs of bits:
dst = src;
dst = ((dst & 0xF0) >> 4) | ((dst & 0x0F) << 4);
dst = ((dst & 0xCC) >> 2) | ((dst & 0x33) << 2);
You may find this helpful:
http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
but it the bit reversal there isn't exactly what you need. With just a little work you could change the "obvious" algorithm to do what you want.
source byte: [01][23][45][67] to
destination: [67][45][23][01]
Implementation:
unsigned char shiftit( unsigned char in ) {
unsigned char out;
out = (
(( in & 0xC0 ) >> 6) + /* top 2 to bottom 2 */
(( in & 0x30 ) >> 2) + /* centre-left 2 to centre-right */
(( in & 0x0C ) << 2) + /* centre-right 2 to centre-left */
(( in & 0x03 ) << 6) /* bottom 2 to top 2 */
);
return( out );
}
Returns 116 when called shiftit( 29 ).
Rotate through carry http://en.wikipedia.org/wiki/Bitwise_operation#Rotate_through_carry
So this would work:
myByte = myByte << 2 | myByte >> 6;