left shift then right shift an unsigned int

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Wenjie

    left shift then right shift an unsigned int

    Hello, for the following code:
    unsigned int var = 0xFF2277F0UL;
    unsigned char take2 = (var << 8) >> 24;
    Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)


    Thanks and best regards,
    Wenjie
  • Bob Hairgrove

    #2
    Re: left shift then right shift an unsigned int

    On 11 Jul 2003 04:07:43 -0700, gokkog@yahoo.co m (Wenjie) wrote:
    [color=blue]
    >Hello, for the following code:
    > unsigned int var = 0xFF2277F0UL;
    > unsigned char take2 = (var << 8) >> 24;
    >Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)[/color]

    It looks OK to me...


    --
    Bob Hairgrove
    rhairgroveNoSpa m@Pleasebigfoot .com

    Comment

    • Ron Natalie

      #3
      Re: left shift then right shift an unsigned int


      "Greg Schmidt" <gregs@trawna.c om> wrote in message news:6k0ugvsn92 ecngaglqeqlfcs4 1s5iane4e@4ax.c om...[color=blue]
      > On 11 Jul 2003 04:07:43 -0700, gokkog@yahoo.co m (Wenjie) wrote:
      >[color=green]
      > >Hello, for the following code:
      > > unsigned int var = 0xFF2277F0UL;
      > > unsigned char take2 = (var << 8) >> 24;
      > >Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)[/color]
      >
      > As others have said, it looks fine, but it seems to me that
      > unsigned int var = 0xFF2277F0UL;
      > unsigned char take2 = (var >> 16) & 0xFF;
      > might be clearer as to the purpose, and easier to modify down the road.[/color]

      I don't know what your assumptions are (since you hardcoded a lot of numbers
      here), but if char is an 8 bit quantity, even the & 0xFF is superfluous.


      Comment

      • Ron Samuel Klatchko

        #4
        Re: left shift then right shift an unsigned int

        gokkog@yahoo.co m (Wenjie) wrote in message news:<d2804eb3. 0307110307.1f7e 3d40@posting.go ogle.com>...[color=blue]
        > Hello, for the following code:
        > unsigned int var = 0xFF2277F0UL;
        > unsigned char take2 = (var << 8) >> 24;
        > Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)[/color]

        One pitfall is that it is dependent on the size of an unsigned int to
        get the expected results. If unsigned int holds more then 32 bits,
        the << 8 won't do the intended stripping.

        Even worse, I think it isn't clear what this code is doing. I can
        picture someone accidentally changing the code to:

        var >> 16;

        If I were writing the code, I'd making the stripping more explicit.

        (var >> 16) & 0xFF

        or possibly:

        (var & 0xFF0000) >> 16

        samuel

        Comment

        Working...