gpt4 book ai didi

c++ - 如何将 stringstream 十六进制字符串字符对转换为单个 uint8_t 等效二进制值

转载 作者:行者123 更新时间:2023-12-02 10:29:39 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:
我有一个组装好的 ostringstream 对象,其中包含要传输的十六进制有效负载。说,可能是

03125412349876543210af     (this is representing the data using hex convention in my string)
该字符串代表 11 个字节,因此例如要传输的最后一个字节是 0xaf(两个字符给我 8 位实际数据)。
我希望读取每对字符,例如字符串中的 '03' 对字符并将其转换为 uint8_t 元素,我将把它推送到 uint8_t 元素的 vector 上。本质上,我将根据字符串的内容创建一个新的 uint8_t 元素 vector ,然后传输该 vector 。
我下面的测试程序适用于“int”,但没有给我想要的 uint8_t。是否有一种优雅和/或直接的方式来做我想做的任何人都可以建议的事情?
(注意:示例 3 是为了看看如果使用了非 hex-legal 值会发生什么。在示例 1 中,像 34r0 这样的值会将 34(hex) 转换为等效的 int 并忽略 r 及其后面的所有内容)。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
cout << "Hello world!" << endl;

// example 1: making a hex string an int - works
std::stringstream str1;
std::string s1 = "5f";
str1 << s1;
int value1;
str1 >> std::hex >> value1;
cout << value1 << endl; // produces 95 - perfect

cout << "~~~~~~~~~" << endl;

// example 2: making a hex string a uint8 - not the result I want
std::stringstream str2;
std::string s2 = "5f";
str2 << s2;
uint8_t value2;
str2 >> std::hex >> value2;
cout << value2 << endl; // produces 5 - not what I want!

cout << "~~~~~~~~~~~" << endl;

// example 3: using non-hex values
std::stringstream str3;
std::string s3 = "wx";
str3 << s3;
uint8_t value3;
str3 >> std::hex >> value3;
cout << value3 << endl; // produces w - not what I want!

// this does not work either
uint8_t value4;
cout << "~~~~~~~~~~~~~~" << endl;
value4 = (uint8_t)value1;
cout << value4 << endl; // produces - - not what I want!

cout << "............." << endl;


return 0;
}
此测试程序的输出如下所示:
Hello world!
95
~~~~~~~~~
5
~~~~~~~~~~~
w
~~~~~~~~~~~~~~
_
.............

Process returned 0 (0x0) execution time : 0.022 s
Press any key to continue.

示例 1 工作正常,但使用 int - 这不是我需要的。

最佳答案

在示例 2 中,您正在提取 uint8_t , 8 位,所以一个 char从字符串中,5 .
在示例 3 中是相同的,您提取第一个字符,所以 w .
对于最后一个示例,它打印 char (8 位),95是 ASCII -特点。如果要显示号码,cast值为 int .

value4 = (uint8_t)value1;
cout << (int)value4 << endl;

关于c++ - 如何将 stringstream 十六进制字符串字符对转换为单个 uint8_t 等效二进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62837206/

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