有没有什么“标准"?C++ 中 64 位整数的类似 htonl 的函数? [英] Is there any "standard" htonl-like function for 64 bits integers in C++?

查看:37
本文介绍了有没有什么“标准"?C++ 中 64 位整数的类似 htonl 的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 memcache 协议的实现,该协议在某些时候使用 64 位整数值.这些值必须以网络字节顺序"存储.

I'm working on an implementation of the memcache protocol which, at some points, uses 64 bits integer values. These values must be stored in "network byte order".

我希望有一些 uint64_t htonll(uint64_t value) 函数来进行更改,但不幸的是,如果它存在,我找不到它.

I wish there was some uint64_t htonll(uint64_t value) function to do the change, but unfortunately, if it exist, I couldn't find it.

所以我有 1 或 2 个问题:

So I have 1 or 2 questions:

  • 是否有任何便携式(Windows、Linux、AIX)标准函数来执行此操作?
  • 如果没有这样的功能,你会如何实现?
  • Is there any portable (Windows, Linux, AIX) standard function to do this ?
  • If there is no such function, how would you implement it ?

我想到了一个基本的实现,但我不知道如何在编译时检查字节序以使代码可移植.所以在这里非常欢迎你的帮助;)

I have in mind a basic implementation but I don't know how to check the endianness at compile-time to make the code portable. So your help is more than welcome here ;)

谢谢.

这是我写的最终解决方案,感谢布赖恩的解决方案.

Here is the final solution I wrote, thanks to Brian's solution.

uint64_t htonll(uint64_t value)
{
    // The answer is 42
    static const int num = 42;

    // Check the endianness
    if (*reinterpret_cast<const char*>(&num) == num)
    {
        const uint32_t high_part = htonl(static_cast<uint32_t>(value >> 32));
        const uint32_t low_part = htonl(static_cast<uint32_t>(value & 0xFFFFFFFFLL));

        return (static_cast<uint64_t>(low_part) << 32) | high_part;
    } else
    {
        return value;
    }
}

推荐答案

您可能正在寻找 bswap_64 我认为几乎所有地方都支持它,但我不会称之为标准.

You are probably looking for bswap_64 I think it is supported pretty much everywhere but I wouldn't call it standard.

您可以通过创建一个值为 1 的 int,将您的 int 的地址转换为 char* 并检查第一个字节的值来轻松检查字节序.

You can easily check the endianness by creating an int with a value of 1, casting your int's address as a char* and checking the value of the first byte.

例如:

int num = 42;
if(*(char *)&num == 42)
{
   //Little Endian
}
else
{
   //Big Endian
} 

知道了这一点,您还可以制作一个简单的函数来进行交换.

Knowing this you could also make a simple function that does the swapping.

您也可以始终使用包含可移植跨平台的字节序宏的 boost.

You could also always use boost which contains endian macros which are portable cross platform.

这篇关于有没有什么“标准"?C++ 中 64 位整数的类似 htonl 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆