C++ 如何在单个块中显示十六进制值

C++ 如何在单个块中显示十六进制值,c++,winapi,char,C++,Winapi,Char,下面的代码在通过循环时逐个显示testbuffer的十六进制代码 char testBuffer[5] = {0x42, 0x54, 0x43, 0x56, 0x42}; for (int i=0; i<5; i++) { char temp[255]; sprintf(temp, _T("%X"), testBuffer[i]); HWND hWnd = GetDlgItem(hDlg, IDC_STATIC_READ); if(hWnd) {

下面的代码在通过循环时逐个显示testbuffer的十六进制代码

char testBuffer[5] = {0x42, 0x54, 0x43, 0x56, 0x42};

for (int i=0; i<5; i++)
{
    char temp[255];
    sprintf(temp, _T("%X"), testBuffer[i]);
    HWND hWnd = GetDlgItem(hDlg, IDC_STATIC_READ); 
    if(hWnd)
    {
        SetWindowText(hWnd, temp);
    }
}
chartestbuffer[5]={0x42,0x54,0x43,0x56,0x42};

对于(int i=0;i尝试将每个十六进制值形成一个字符串,concat将它们转换为另一个字符串:

char tempword[16] ;
char temp[255] ;

* tempword= '\0' ;
for (int i= 0; ( i < 5 ) ; i ++ )
{
  sprintf(tempword, "%X", testBuffer[i] ) ;
  strcat( temp, tempword ) ;
}
...
SetWindowText( hWnd, temp ) ;
char-tempword[16];
字符温度[255];
*tempword='\0';
对于(int i=0;(i<5);i++)
{
sprintf(tempword,“%X”,testBuffer[i]);
strcat(临时、临时字);
}
...
设置窗口文本(hWnd、temp);

移动字符串缓冲区的定义,并在循环外部调用
SetWindowText

char testBuffer[5]={0x42,0x54,0x43,0x56,0x42};
char temp[255] = {0};  // zero initialize

for (int i=0; i<5; i++)
{
  sprintf(&temp[strlen(temp)], "%02X", testBuffer[i]);
}

HWND hWnd = GetDlgItem(hDlg, IDC_STATIC_READ); 
if ( hWnd )
{
  SetWindowText(hWnd, temp);
}

对于此版本,您需要包括头文件
ios
iomanip
sstream

Win32的CryptBinaryToString可以方便地使用this@user3048644由于您是StackOverflow新手,如果您发现答案有帮助,可以通过使用
strlen(temp)来说明这一点循环中的
将在循环迭代时逐渐减慢循环速度(在本例中不是很糟糕,但对于较大的缓冲区可能会有问题)。您应该使用一个单独的变量,该变量初始化为0,并在每次
sprint()
后递增,然后使用最终值为零终止缓冲区(避免必须事先将缓冲区初始化为零):
intidx=0;对于(…){idx+=sprintf(&temp[idx],“%02X”,testBuffer[i]);}temp[idx]:=0;
或者,您可以使用循环计数器作为索引:
inti=0;对于(…;++i){sprintf(&temp[i*2],“%02X”,testBuffer[i]);}tmp[i]= 0;我喜欢C++方法,虽然 >(int I:TestBuffic)语法在所有C++编译器中都不可用。
char testBuffer[5]={0x42,0x54,0x43,0x56,0x42};
std::ostringstream oss;

oss << std::hex << std::setfill('0') << std::uppercase;

for(int i : testBuffer) 
{
  oss << std::setw(2) << i;
}

HWND hWnd = GetDlgItem(hDlg, IDC_STATIC_READ); 
if ( hWnd )
{
  SetWindowText(hWnd, oss.str().c_str());
}