简体   繁体   English

如何在C ++中将little-endian 64转换为主机字节顺序

[英]How to convert little-endian 64 to host byte order in C++

I need to convert little-endian 64 to host byte order. 我需要将little-endian 64转换为主机字节顺序。 In winapi i can't find such functions, so i need to write my own, can anyone help me? 在winapi中我找不到这样的函数,因此我需要编写自己的函数,有人可以帮助我吗? Thanks! 谢谢!

Use htonll . 使用htonll It converts an unsigned __int64 to network byte order. 它将无符号的__int64转换为网络字节顺序。

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 ;  

}

In Linux you can use uint64_t htobe64(uint64_t host_64bits); 在Linux中,您可以使用uint64_t htobe64(uint64_t host_64bits);

Check the man page for more details. 有关更多详细信息,请参见man

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. 当然,如果文件在8个字节的中间结束,则确实需要某种错误检查。 (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). 如果数据已经在缓冲区中,则只需将static_cast<unsigned char>(*p++) source.get()source.get() (其中p指向缓冲区中的位置)。 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. 在这种情况下,在进行转换之前 ,还必须确保在初始p和缓冲区末尾之间有8个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM