Thread: Bit Shifting

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    61

    Bit Shifting

    Hi There,
    I apologise if this is really daft but im totally lost.

    I have a unsigned int for example (0x4f1164)

    i am doing the following bit shifting

    sCanMsg.abData[ByteNum] = Data;
    sCanMsg.abData[ByteNum+1] = Data>>8;
    sCanMsg.abData[ByteNum+2] = Data>>16;
    sCanMsg.abData[ByteNum+3] = Data>>24;
    sCanMsg.abData[ByteNum+4] = Data>>32;
    sCanMsg.abData[ByteNum+5] = Data>>40;
    sCanMsg.abData[ByteNum+6] = Data>>48;
    sCanMsg.abData[ByteNum+7] = Data>>56;

    only problem is when i get to the 5 line down it starts the number again so i end up with

    00 4f 11 64 00 4f 11 64

    just 00 4f 11 64

    Can anyone tell me why it seems to have the value twice?

    thanks

    James

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    How many bits in a "unsigned int" on your system?
    If 32 bits, then shifting more than 32 bits is undefined.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Left shift ex << n is defined as ex * 2^n so when you shift you should want to move the ex n places to the left (assuming big endian).

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Step 1: Turn it into a loop:
    Step 2: Make the loop go up until shift_size equals sizeof the variable concerned.
    Step 3: Fill the remaining bytes with zeros using memset.

    Step 4 would be switch to C++ and make use of template specialisation, but I wont push that idea right now.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Shifting???
    By programmer1 in forum C Programming
    Replies: 4
    Last Post: 11-10-2011, 05:48 PM
  2. bit shifting
    By zecamoraes in forum C Programming
    Replies: 8
    Last Post: 11-24-2003, 10:41 AM
  3. bit shifting
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 07-14-2002, 12:31 AM
  4. bit shifting
    By cppdude in forum C++ Programming
    Replies: 9
    Last Post: 03-23-2002, 05:19 PM