2017年3月31日 星期五

在Command中顯示像RW編排的內容

有時程式除錯需要列印一大塊的記憶體空間內容,在無法借助外部程式的情況下,就需要用程式來印,筆者花點時間分享一下自己除錯會用到的程式碼。
程式碼如下:
void CWizardMan::PrintData(UCHAR * ucptr, int nLength)
{
 int i, j, nRemainLength = 0, nCurrentLength = 0;
 CString csTemp = "", csTemp1 = "", csTemp2 = ""; 
 CString cs;

 cs.Format("Print Buffer data, size = %d", nLength);
 OutputDebugString(cs);

 //前面16進制顯示
 for(i = 0 ; i < 16; i++)
 {
  csTemp.Format("%02X ", i);
  csTemp1 += csTemp;
 }
 csTemp1 = "       |   " + csTemp1;

 //空白
 for(i = 1 ; i <= 80 - csTemp1.GetLength() - 16; i++)
 {
  csTemp.Format(" ");
  csTemp2 += csTemp; 
 } 

 //後面ASCCII顯示
 for(i = 0 ; i < 16; i++)
 {
  csTemp.Format("%X", i);
  csTemp2 += csTemp;
 }
 csTemp = csTemp1 + csTemp2;
 csTemp1 = "";
 csTemp2 = "";

 cs.Format("%s", csTemp);
 OutputDebugString(cs);
 OutputDebugString("-------------------------------------------------------------------------------------------------------");

 nRemainLength = nLength;
 for(i = 0 ; i < nLength ; i+=16)
 {
  if(nRemainLength > 16)
   nCurrentLength = 16;
  else
   nCurrentLength = nRemainLength;

  //前面16進制顯示
  for(j = 1 ; j <= nCurrentLength ; j++)
  {
   if(j > 10 && j < 15)
    csTemp.Format("%02X  ", ucptr[i+j-1]);
   else
    csTemp.Format("%02X ", ucptr[i+j-1]);
   csTemp1 += csTemp; 
  }

  csTemp.Format("%03X |   ", i);
  csTemp1 = csTemp + csTemp1 ;

  //空白  
  for(j = 1 ; j <= 80 - csTemp1.GetLength() - 16 ; j++)
  {
   csTemp.Format(" ");
   csTemp2 += csTemp; 
  } 

  //後面ASCCII顯示
  for(j = 1 ; j <= nCurrentLength ; j++)
  {
   if((ucptr[i + j - 1] <= 0x20) || (ucptr[i + j - 1] > 0x7F))
    csTemp.Format(".");
   else
    csTemp.Format("%c", ucptr[i + j - 1]);
   csTemp2 += csTemp;  
  }

  csTemp = csTemp1 + csTemp2;
  csTemp1 = "";
  csTemp2 = "";  
  nRemainLength -= 16;
  cs.Format("%s", csTemp);
  OutputDebugString(cs);
 }
 OutputDebugString("-------------------------------------------------------------------------------------------------------");
}