简体   繁体   English

C ++字节字符串转换为字节数据类型并计数字节

[英]C++ String of Bytes convert to byte datatype and count bytes

As the title says I try to convert to byte data type a C++ String of Bytes and count bytes. 如标题所述,我尝试将C ++字节字符串转换为字节数据并计数字节。 The string I get from textbox will contain a series of one byte hexadecimal numbers, but I need to send it as bytes. 我从文本框中获取的字符串将包含一系列一个字节的十六进制数字,但是我需要将其作为字节发送。

char packet_data[200];
HWND hTextBox2 = GetDlgItem(TabOneDlg,IDC_EDIT3);

SendMessageA(hTextBox2, WM_GETTEXT, (WPARAM)200, (LPARAM)packet_data);

That's how I get the input value (I am using win32 API - unmanaged forms) 这就是我获取输入值的方式(我正在使用Win32 API-非托管形式)

EXAMPLE of input string (hex) 输入字符串示例(十六进制)

AA BB CC DD - 4 bytes !

In SHORT I want to do this : Got a string containing a textual representation of hexadecimal numbers, and I want to convert each textual representation of the hexadecimal numbers to "normal" numbers. 在SHORT中,我想这样做:得到了一个包含十六进制数字文本表示形式的字符串,并且我想将十六进制数字的每个文本表示形式转换为“正常”数字。

If you are sure that the hexadecimal numbers are separated by a space (as shown in the question) it is a simple question of extracting them. 如果您确定十六进制数之间用空格隔开(如问题所示),则提取它们是一个简单的问题。 The simplest way in C++ is by using std::istringstream and the normal input operator >> : C ++中最简单的方法是使用std::istringstream和常规输入运算符>>

std::istringstream istr(packet_data);
std::vector<uint8_t> data;

uint8_t i;
while (istr >> std::hex >> i)
    data.push_back(i);

After the above code, the vector data will have all data from the string. 在上面的代码之后,向量data将包含字符串中的所有数据。 If you need to eg send the data over a socket (or similar) you can use std::vector::data to get a raw pointer to the data (or use &data[0] if the data function doesn't exist), and the number of bytes is available from std::vector::size . 如果您需要例如通过套接字(或类似接口)发送数据,则可以使用std::vector::data获取指向数据的原始指针(如果data功能不存在,则使用&data[0] ),字节数可从std::vector::size

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

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