# Thread: Swap Nibbles

1. ## Swap Nibbles

A nibble is a group of 4 bits. Write a function that given an unsigned n returns the value with the nibbles placed in reverse order.

Code:
```#include <stdio.h>
unsigned swap_nibbles(unsigned n){
unsigned newNumber = 0;
unsigned nBits = sizeof(unsigned) * 8;
unsigned firstHalf = n << (nBits / 2);
unsigned secondHalf = n >> (nBits / 2);
newNumber =
return newNumber;

}
int main(){
unsigned a = 0x5A;
printf("The initial number is %d\n", a);
printf("The new number with the nibbles swapped is %x", swap_nibbles(a)); //A5000000000000
return 0;
}```
I need to know what bitwise operations should I use, in order to switch firstHalf and secondHalf in newNumber (my guess would be XOR), but I don't know how I could write this. 2. The goal is to "returns the value with the nibbles placed in reverse order", not to swap the first half of the bits with the second half of the bits (although that would be equivalent if there were only 8 bits, but unsigned int must have at least 16 bits to mathematically conform to the standard's requirements on minimum ranges). 3. Originally Posted by laserlight The goal is to "returns the value with the nibbles placed in reverse order", not to swap the first half of the bits with the second half of the bits (although that would be equivalent if there were only 8 bits, but unsigned int must have at least 16 bits to mathematically conform to the standard's requirements on minimum ranges).
Well I thought about it as being a 32-bit number, and the first half would 16 bits and the second half the other 16 bits. Wouldn't it work this way? 4. Originally Posted by rmmstn Well I thought about it as being a 32-bit number, and the first half would 16 bits and the second half the other 16 bits. Wouldn't it work this way?
A nibble is always four bits. So a 32 bit value has 8 nibbles.

Here's a hint:

Code:
```   unsigned a = 0
a = (a << 4) + 1;
a = (a << 4) + 2;
a = (a << 4) + 3;
a = (a << 4) + 4;
a = (a << 4) + 5;
a = (a << 4) + 6;
a = (a << 4) + 7;
a = (a << 4) + 8;```
What is a (in hex) at the end of this code? 5. Originally Posted by hamster_nz A nibble is always four bits. So a 32 bit value has 8 nibbles.

Here's a hint:

Code:
```   unsigned a = 0
a = (a << 4) + 1;
a = (a << 4) + 2;
a = (a << 4) + 3;
a = (a << 4) + 4;
a = (a << 4) + 5;
a = (a << 4) + 6;
a = (a << 4) + 7;
a = (a << 4) + 8;```
What is a (in hex) at the end of this code?
Code:
```unsigned a = 0;
a = (a << 4) + 1; //a = 0 * 2^4 + 1 = 1
a = (a << 4) + 2; //a = 1 * 2^4 + 2 = 18
a = (a << 4) + 3; //a = 18 * 2^4 +3 = 291
a = (a << 4) + 4; //a = 291 * 2^4 + 4 = 4660
a = (a << 4) + 5; //a = 4660 * 2^4 + 5 = 74565
a = (a << 4) + 6; //a = 74565 * 2^4 + 6 = 1193046
a = (a << 4) + 7; //a = 1193046 * 2^4 +7 = 19088743
a = (a << 4) + 8; //a = 19088743 * 2^4 + 8 = 305419896
printf("0x%x", a); //12345678``` Popular pages Recent additions #### Tags for this Thread

bitwise operators, newnumber, nibbles, return, unsigned 