3

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!

Nick
  • 25,026
  • 7
  • 51
  • 83
lebron2323
  • 990
  • 2
  • 14
  • 29
  • 1
    Considering 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
  • 1
    A 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 Answers4

3

Use htonll. It converts an unsigned __int64 to network byte order.

Sean
  • 60,939
  • 11
  • 97
  • 136
2

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 ;  

}
Pandrei
  • 4,843
  • 3
  • 27
  • 44
2

In Linux you can use uint64_t htobe64(uint64_t host_64bits);

Check the man page for more details.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Rahul_cs12
  • 974
  • 1
  • 13
  • 22
1

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329