I need to convert little-endian 64 to host byte order. In winapi i can't find such functions, so i need to write my own, can anyone help me? Thanks!
- 
                    1Considering that you mention "winapi" I guess you're on a Windows system, which means that unless you're on a **very** old system (we're talking 1990's when Windows NT was ported to some big-endian machines) chances are that you're on a x86/x86_64 system, which already is little-endian. So converting little-endian to little-endian is a no-op. – Some programmer dude Jan 23 '14 at 08:29
- 
                    1A quick search on google returns http://stackoverflow.com/questions/2182002/convert-big-endian-to-little-endian-in-c-without-using-provided-func as the top result - it has some answers you might find useful. – Nick Jan 23 '14 at 08:35
4 Answers
- 
                    5It should be noted that this is not a portable function, it's Windows only. – Some programmer dude Jan 23 '14 at 09:15
- 
                    1@JoachimPileborg - yes, but the questioner mentions the Windows API in his question, so it seems reasonable. – Sean Jan 23 '14 at 09:42
- 
                    This converts host order to network byte order which is big endian. The OP asked for converting little endian to host order. – Andre Holzner Sep 10 '21 at 13:22
I think you need to get the host's endiannes first and you can decide after that if you need to convert anything:
#define BIG_ENDIAN 1
#define LITTLE_ENDIAN 0
int getEndiannes()
{
   int n = 1;
   char *p = &n;
   if(*p) 
       return LITTLE_ENDIAN; 
   else
       return BIG_ENDIAN ;  
}
 
    
    - 4,843
- 3
- 27
- 44
In Linux you can use uint64_t htobe64(uint64_t host_64bits);
Check the man page for more details.
 
    
    - 167,307
- 17
- 350
- 455
 
    
    - 974
- 1
- 13
- 22
If you're reading external data, the usual solution is to build up the individual values as specified:
unsigned long long      //  The only type guaranteed long enough for 64 bits
readData( std::istream& source )
{
    unsigned long long results = source.get();
    results |= source.get() <<  8;
    results |= source.get() << 16;
    results |= source.get() << 24;
    results |= source.get() << 32;
    results |= source.get() << 40;
    results |= source.get() << 48;
    results |= source.get() << 56;
    return results;
}
Of course, you really need some sort of error checking, in case the file ends in the middle of the 8 bytes. (But it is sufficient to check once, after all of the bytes have been read.)
If the data is already in a buffer, then just substitute
static_cast<unsigned char>(*p++) for source.get() (where p
points to the position in the buffer).  In this case, you also
have to ensure that there are 8 bytes between the initial p
and the end of the buffer before doing the conversion.
 
    
    - 150,581
- 18
- 184
- 329
 
     
    