C++ Builder
??今天调试GUI程序,需要将网络接收的数据流(char*)以十六进制的格式打印到日志窗口上。
String PrintHex(char *data, int len)
{
char alphabet[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
String s;
for (int i=0; i<len; i++) {
int l = (int)(data[i]&0x0f);
int h = (int)(data[i]>>4)&0x0f;
s += alphabet[h];
s += alphabet[l];
s += " ";
}
return s;
}
在后来的调试过程中发现当传输的数据比较复杂的时候,这样直接的打印字节序列很难定位到某个具体元素在序列中的位置,为此在前面程序的基础上添加了显示地址的功能。
String PrintHex(char *data, int len)
{
char alphabet[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
String s;
int l,h;
for (int i=0; i<len; i++) {
if (i % 8 == 0) {
s += "\r\n";
char start = (i/8)*8;
l = (int)(start&0x0f);
h = (int)(start>>4)&0x0f;
s += alphabet[h];
s += alphabet[l];
s += "~";
char end = (i/8+1)*8-1;
l = (int)(end&0x0f);
h = (int)(end>>4)&0x0f;
s += alphabet[h];
s += alphabet[l];
s += ": ";
}
l = (int)(data[i]&0x0f);
h = (int)(data[i]>>4)&0x0f;
s += alphabet[h];
s += alphabet[l];
s += " ";
}
return s;
}
以下是调试过程中一个输出案例。
00~07: 11 42 00 01 a3 65 00 00
08~0f: 00 00 00 40 59 40 00 00
10~17: 00 00 00 c0 59 40 00 00
18~1f: 00 00 00 80 59 40 00 00
20~27: 00 00 00 40 5a 40 6a 00
28~2f: 00 00 00 00 00 c0 5a 40
30~37: 00 00 00 00 00 00 26 40
38~3f: 22 00 00 00 0d 0e 07 fb
40~47: 0d 0a
|