std::hex 没有像我预期的那样工作
std::hex does not work as I expect
我不习惯C++,所以请耐心等待...
从设备读取两个字节并进入缓冲区。然后打印出来。
下面的代码应该返回字符串"0x204D"但是,它返回"0x M",十六进制为 30 78 20 4d
因此,十六进制不会解码为 ascii。
void vito_unit::decodeAsRaw(unsigned char *buffer, int bufferLen)
{
std::stringstream *decodedClearText;
decodedClearText = new std::stringstream;
*decodedClearText << "0x" << std::hex;
for (int i=0; i<bufferLen; i++) {
*decodedClearText << buffer[i];
}
setValue(decodedClearText->str());
}
应该怎么做?
这与
std::hex
无关。
当您流式传输[signed/unsigned] char
时,将使用其 ASCII 表示形式,因为这通常是char
s的预期。
转换为 int
来流式传输号码。然后以十六进制表示法呈现数字的功能(即 std::hex
( 将被触发。
您还应该修复内存泄漏和不必要的动态分配:
void vito_unit::decodeAsRaw(unsigned char const* const buffer, int const bufferLen)
{
std::stringstream decodedClearText;
decodedClearText << "0x" << std::hex;
for (int i = 0; i < bufferLen; i++) {
decodedClearText << +buffer[i];
}
setValue(decodedClearText.str());
}
一元"+"执行对int
的积分提升。
buffer[i]
的类型为 unsigned char
,因此打印为字符而不是其十六进制表示形式。可以将值强制转换为unsigned int
以避免这种情况。
void vito_unit::decodeAsRaw(unsigned char *buffer, int bufferLen)
{
std::stringstream *decodedClearText;
decodedClearText = new std::stringstream;
*decodedClearText << "0x" << std::hex;
for (int i=0; i<bufferLen; i++) {
*decodedClearText << (unsigned int) buffer[i];
}
setValue(decodedClearText->str());
}
Bo Persson的提示是我需要的。
for (int i=0; i<bufferLen; i++) {
*decodedClearText << (int)buffer[i];
}
做到了。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- HEX值到wchar_t字符(UTF-8)的转换
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- std::hex 没有像我预期的那样工作
- Std::hex/ Std::oct不工作(打印十进制值)