Converting 8 bytes to integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mjbauer95
    New Member
    • Jan 2009
    • 13

    Converting 8 bytes to integer

    I am working with a binary file and I have 8 bytes that I want to convert to an integer.

    This way works:
    Code:
    unsigned char buf[1024];
    long long value;
    
    value = ((long long)buf[0]<<56) | ((long long)buf[1]<<48) | ((long long)buf[2]<<40) | ((long long)buf[3]<<32) | (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
    
    printf("%lld\n", value);
    But it's not very elegant. Is there any elegant way to convert 8 bytes to an integer.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That is the way to do it, white space can make it more readable but generally all portable methods will involve doing something similar to what you have done.

    Comment

    • BillyTKid
      New Member
      • Aug 2010
      • 7

      #3
      unsigned long long value;

      if( 1==fread((unsig ned char*)&value,si zeof value,1,FILEptr ) )
      ...
      writing the file e.g.
      if( 1==fwrite((unsi gned char*)&value,si zeof value,1,FILEptr ) )
      ...

      Comment

      Working...