繁体   English   中英

不带itoa / to_string / boost的IP地址字符串的无符号整数

[英]Unsigned int to IP address string without itoa/to_string/boost

寻找一种非常快速有效的方法,将无符号的32位int转换为IP地址std :: string而不使用itoa或to_string或boost。 我们当前的版本不支持其中任何一个。 而且,这将在我们的系统上运行多次,因此必须快速。

例如,无符号32位int的每个8位段都将转换为八位字节之一,直到int的所有32位都被转换为止。 是否正在考虑使用printf ...还有更好的方法吗?

16909060-> 0x01020304-> 00000001000000100000001100000100-> 1.2.3.4

也许你想要:

char buf[16];
snprintf(buf, sizeof buf, "%u.%u.%u.%u", 
    (x / 0x1000000u) % 0x100,
    (x / 0x10000u) % 0x100,
    (x / 0x100u) % 0x100,
    (x) % 0x100 );

使用按位运算可以使您轻松检索每个八位位组。 像这样吗 (手头没有编译器)

uint32_t ip = ....;
ip & 0xFF;  // last octet
(ip >> 8) & 0xFF;  // 2nd last octet
(ip >> 16) & 0xFF;  // 2nd octet
ip >> 24; // first octet

暂无
暂无

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

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