将字符串转换为IP地址时输出错误
Wrong output when converting string to IP address
我正在尝试将字符串转换为IP地址。输入字符串为转换为std::string
的无符号整数,例如"123456"
。下面的代码是不正确的,因为它产生不可读的二进制字符。
std::string str2IP(const std::string& address)
{
uint32_t ip = std::strtoul(address.c_str(), NULL, 0);
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
std::stringstream ss;
ss << bytes[3] << "." << bytes[2] << "." << bytes[1] << "." << bytes[0];
return ss.str();
}
I/O流的格式化输出函数(操作符<<
)将char
, signed char
和unsigned char
视为字符—它们将值解释为字符代码,而不是数字。这段代码将输出A
:
unsigned char c = 65;
std::cout << c;
在大多数实现中,std::uint8_t
也是如此,因为它们只是将其用作typedef
到unsigned char
。您需要使用合适的数字类型,例如unsigned short
:
std::string str2IP(const std::string& address)
{
uint32_t ip = std::strtoul(address.c_str(), NULL, 0);
unsigned short bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
std::stringstream ss;
ss << bytes[3] << "." << bytes[2] << "." << bytes[1] << "." << bytes[0];
return ss.str();
}
将char
s输出到std::stringstream
具有输出由该char
表示的编码字符而不是数字表示的语义。
您可以通过使用一元加号来强制使用数字表示来提升那些char
s:
ss << +bytes[3] << "." << +bytes[2] << "." << +bytes[1] << "." << +bytes[0];
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 使用复制构造函数的程序输出错误
- 异或字符串加密/解密输出错误
- 在linux上使用g++输出错误,在windows上更正
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- ECDSA 密钥对生成输出错误
- fscanf() 输出错误的值
- 输入 1024 后十进制到二进制转换的输出错误?
- 输出错误命令的条件语句
- cuSparse (cusparseDcsrgemm) 中的矩阵乘法输出错误的结果
- 为什么 du -sh 输出错误大小的内存映射文件
- VS2017 的输出错误,但 mingw 有效
- 如何使FFMPEG C 代码不输出错误消息
- 乘以时输出错误.这是我编译器中的错误吗?C
- 输出错误:两个不同编译器上的不同输出:Prime Cryptarithm USACO
- 为什么输出错误崩溃
- C++输入/输出错误
- 尝试用 c++ 制作一个简单的加法器.编译成功,但输出错误
- 当我使用此合并排序代码运行时,输出错误
- 递归功能输出错误的值