将IDC_Edit文本转换为十六进制的WORD
Converting IDC_Edit text to hexadecimal WORD
我有一个IDC_Edit文本框集,它将接受十六进制空格分隔的值,我想转换为WORD。我想要的控制模拟数组,但我真的不确定如何完成转换。
基本上,如果我输入:"12 AB"
我需要生成的WORD等于:
0x12AB
作为一个很少接触c++的人,更不用说WinAPI了,我真的很难为如何做到这一点。我现在的代码是:
HWND hTextInput = GetDlgItem(hWnd, IDC_EDIT);
DWORD dwInputLength = Edit_GetTextLength(hTextInput);
char* resultString = new char[dwInputLength+1];
memset(hTextInput , 0, dwInputLength+1);
WORD result = (resultString[0] << 8) | resultString[1];
这将提取IDC_EDIT
控件的文本和长度,并将其转换为char*
数组。然后尝试将其转换为WORD,但显然目前只接受前两个字符(12
)。
我怎样才能把"12 AB"
拉进char*
数组作为[0x12, 0xAB]
(而不是["1", "2", "A", "B"]
),这样我就可以把两个字节转换成一个WORD?
试试这个:
WORD Readhex(const char *p)
{
char c ;
WORD result = 0 ;
while (c = *p++)
{
if (c >= '0' && c <= '9')
c -= '0' ;
else if (c >= 'A' && c <= 'F')
c -= 'A' - 10 ;
else if (c >= 'a' && c <= 'f')
c -= 'a' - 10 ;
else
continue ;
result = (result << 4) + c ;
}
return result ;
}
...
HWND hTextInput = GetDlgItem(hWnd, IDC_EDIT);
DWORD dwInputLength = Edit_GetTextLength(hTextInput);
char* resultString = new char[dwInputLength+1];
GetWindowText(hTextInput, resultString, dwInputLength+1) ;
WORD result = ReadHex(resultString) ;
你还忘了GetWindowText;用零(memset)填充缓冲区是不必要的。所建议的strtol函数将不适合您,因为strtol将把空格视为终止符。也许您还应该考虑进行一些错误检查,例如,如果用户输入了垃圾。上面的ReadHex函数只是忽略任何非十六进制数字。
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 打印十六进制字符
- 将IDC_Edit文本转换为十六进制的WORD