-
Bit SHIFT ISSUES
Hi there,
I am just looking for some advice on Bit shifting.
I have a program that will split a 32bit into its 4 bytes. This works to a certain extent:
I get the following when i run the snippet of code below:
Original HEX NUMBER: CD53BB10;
BYTE1: CD
BYTE2 : 53
BYTE3: BB
BYTE4: 1
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int n = 0xCD53BB10;
unsigned int shift =0xFF000000 ;
unsigned int byte1,byte2,byte3,byte4;
printf("Original Hex Number: %X\n\n\n",n);
byte1=(n ) & shift;
byte1 = byte1 >> 24;
printf("\nByte1 =%X",byte1);
shift = 0xFF0000;
byte2=(n ) & shift;
byte2 = byte2 >> 16;
printf("\nByte2 =%X",byte2);
shift = 0xFF00;
byte3=(n ) & shift;
byte3 = byte3 >> 8;
printf("\nByte3 =%X",byte3);
shift = 0xFF;
byte4=(n ) & shift;
byte4 = byte4 >> 4;
printf("\nByte4 =%X",byte4);
printf("\n\n");
system("pause");
return 0;
}
One thing that I am stuck on is the shifting off the hex number 0xFF000000. The only way that I can get it to work is to manually input the number with the last 2 LSB taken off as in the code above. How do i do this automatically? Also when i try and retrieve the last 2 bytes i only get 1 character printed out...
thanks in advance
-
I think your only mistake is that you shifted the last byte to the right by a nibble, resulting in an answer of 0x1.
As for your other question, observe that a byte is actually 8 bits.
Code:
#include <stdio.h>
int main(void)
{
unsigned x;
for ( x = 0xcd53bb10; x > 0; x >>= 8 )
{
printf( "0x%x\n", x );
}
return 0;
}
#if 0
0xcd53bb10
0xcd53bb
0xcd53
0xcd
#endif
So now you know how to adjust the shift.