-1

I have an IDC_Edit text box set which will accept hexadecimal space-separated values that I'm wanting to convert into a WORD. I'm wanting the control to mimic the array, but I'm really unsure how to complete the conversion.

Basically, if I input:

"12 AB"

I need the resulting WORD to equal:

0x12AB

As someone who rarely dabbles with C++, let alone the WinAPI, I'm really stumped as to how to do this. My current code is:

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];

This pulls the IDC_EDIT control's text and length and turns it into a char* array. This then attempts to convert into a WORD, but obviously this only currently takes the first two characters (12) in this case.

How can I make this pull "12 AB" into the char* array as [0x12, 0xAB] (rather than ["1", "2", "A", "B"]) so that I can then shift the two bytes into a WORD?

4

1 回答 1

1

尝试这个:

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 函数简单地忽略任何非十六进制数字。

于 2013-05-06T08:43:38.033 回答