gpt4 book ai didi

c++ - 将无符号字符数组转换为 IP 字符串的最快方法是什么

转载 作者:太空狗 更新时间:2023-10-29 23:50:02 24 4
gpt4 key购买 nike

我需要(或多或少)实时处理其中的许多内容。我目前使用的方法不再削减它。

std::string parse_ipv4_address( const std::vector<unsigned char> & data, int start )
{
char ip_addr[16];
snprintf( ip_addr, sizeof(ip_addr), "%d.%d.%d.%d",
data[start + 0], data[start + 1], data[start + 2], data[start + 3] );
return std::string( ip_addr );
}

// used like this
std::vector<unsigned char> ip = { 0xc0, 0xa8, 0x20, 0x0c };
std::string ip_address = parse_ipv4_address( ip, 0 );

std::cout << ip_address << std::endl; // not actually printed in real code
// produces 192.168.32.12

有没有更快的方法呢?以及如何?

注意!性能是这里的问题 this issue不是重复的。

最佳答案

以下是影响性能的潜在候选对象:

  • snprintf 需要解析格式字符串,并进行错误处理。要么花费时间,要么实现您不需要的功能。
  • 在返回时构造一个 std::string 对象是昂贵的。它将受控序列存储在自由存储内存(通常实现为堆内存)中,这在 C++(和 C)中分配成本有点高。
  • 使用 std::vector 存储 4 字节值会不必要地消耗资源。它还在自由存储中分配内存。将其替换为 char[4] 或 32 位整数 (uint32_t)。

由于您不需要 printf 系列函数的多功能性,您可能会完全放弃它,而改用查找表。查找表由 256 个条目组成,每个条目都包含字节值 0 到 255 的可视化表示。要对此进行优化,让 LUT 也包含尾随 . 字符。 (需要特别注意,以解决字节序问题。我假设这里是小端字节序。)

解决方案可能如下所示1):

const uint32_t mapping[] = { 0x2E303030, // "000."
0x2E313030, // "001."
// ...
0x2E343532, // "254."
0x2E353532 // "255."
};

alignas(uint32_t) char ip_addr[16];
uint32_t* p = reinterpret_cast<uint32_t*>(&ip_addr[0]);
p[0] = mapping[data[0]];
p[1] = mapping[data[1]];
p[2] = mapping[data[2]];
p[3] = mapping[data[3]];

// Zero-terminate string (overwriting the superfluous trailing .-character)
ip_addr[15] = '\0';

// As a final step, waste all the hard earned savings by constructing a std::string.
// (as an ironic twist, let's pick the c'tor with the best performance)
return std::string(&ip_addr[0], &ip_addr[15]);

// A more serious approach would either return the array (ip_addr), or have the caller
// pass in a pre-allocated array for output.
return ip_addr;


1) 免责声明:从char* 转换为uint32_t* 在技术上表现出 未定义的行为。 不要使用,除非您的平台(编译器和操作系统)提供额外的保证来明确定义。

关于c++ - 将无符号字符数组转换为 IP 字符串的最快方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34334239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com