将IDC_Edit文本转换为十六进制的WORD

Converting IDC_Edit text to hexadecimal WORD

本文关键字:十六进制 WORD 转换 文本 IDC Edit      更新时间:2023-10-16

我有一个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函数只是忽略任何非十六进制数字。