Efficiently combining bytes into a long int

Hi,

I'm having problems assembling a set of 4 bytes into a long int. My approach has been this:

    ulong temp;
    temp = (temp << SHIFT_BYTE) | getByte();
    temp = (temp << SHIFT_BYTE) | getByte();
    temp = (temp << SHIFT_BYTE) | getByte();
    temp = (temp << SHIFT_BYTE) | getByte();
    return temp;

But this results in a ton of calls to the long int library shift and logical or routines, which really aren't necessary. My quick and dirty solution has been to code the function in assembly, and just put the bytes in the appropriate "temp+n" bytes that make up temp. I've tried fooling around with unions, but haven't had any luck.

Thanks,
Bob

Parents
  • What about this:

    union
      {
      unsigned long lvar;
      unsigned char bytes[4];
      }
    v;
    
    v.bytes[0]=getByte();  //MSB
    v.bytes[1]=getByte();
    v.bytes[2]=getByte();
    v.bytes[3]=getByte();  //LSB
    
    return (v.lvar);
    

    This generates the following:

    0013 120000      R     LCALL   getByte
    0016 8F00        R     MOV     v,R7
    0018 120000      R     LCALL   getByte
    001B 8F00        R     MOV     v+01H,R7
    001D 120000      R     LCALL   getByte
    0020 8F00        R     MOV     v+02H,R7
    0022 120000      R     LCALL   getByte
    0025 8F00        R     MOV     v+03H,R7
    

    Jon

Reply
  • What about this:

    union
      {
      unsigned long lvar;
      unsigned char bytes[4];
      }
    v;
    
    v.bytes[0]=getByte();  //MSB
    v.bytes[1]=getByte();
    v.bytes[2]=getByte();
    v.bytes[3]=getByte();  //LSB
    
    return (v.lvar);
    

    This generates the following:

    0013 120000      R     LCALL   getByte
    0016 8F00        R     MOV     v,R7
    0018 120000      R     LCALL   getByte
    001B 8F00        R     MOV     v+01H,R7
    001D 120000      R     LCALL   getByte
    0020 8F00        R     MOV     v+02H,R7
    0022 120000      R     LCALL   getByte
    0025 8F00        R     MOV     v+03H,R7
    

    Jon

Children
More questions in this forum