Thread: Bit SHIFT ISSUES

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    3

    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
    Last edited by lodey; 02-24-2011 at 06:54 PM. Reason: tidy up code

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bit Sized Variable
    By Crosility in forum C Programming
    Replies: 44
    Last Post: 02-24-2011, 02:17 PM
  2. how can I shift bit right a byte array
    By lovesunset21 in forum C Programming
    Replies: 10
    Last Post: 11-03-2010, 02:31 PM
  3. Caeser Cipher
    By L_U_K_E in forum C++ Programming
    Replies: 35
    Last Post: 06-30-2006, 07:15 AM
  4. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM