Change the endianess of a number

This program is to change the endianess of a number along with swapping the nibble of a byte

Logic:
1) data & 0x000000FF — This picks the first byte from a given number
2) data & 0x0F) — This picks the first four bits of a byte

After picking these we would shift them to their respective position.

#include <stdio.h>

int main()
{
	int data = 0x4523 ;
	printf("\n The original vlaue is %x\n",data);
	printf("\n The changes Endinaess is %x\n", ((data  & 0x000000FF)  <<24) | ((data  & 0x0000FF00) <<8) | ((data  & 0x00FF0000) >>8) | ((data  & 0xFF000000)>>24));
	data =0x23;
	printf("\n The original vlaue is %x\n",data);
	printf("\n Nibble converted data is %x\n", ((data & 0x0F) <<4 | ((data & 0xF0) >>4)));
        
	return 0;
}

Output:

The original vlaue is 4523

The changes Endinaess is 23450000

The original vlaue is 23

Nibble converted data is 32


Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: