编程实现:把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列
1 template <typename T>
2 void displayHexBin(const T& v)
3 {
4 const unsigned char c2h[] = "0123456789ABCDEF";
5 const unsigned char c2b[] = "01";
6
7 unsigned char* p = (unsigned char*)&v;
8 char* buf = new char [sizeof(T)*2+1];
9 char* ptmp = buf;
10 p = p + sizeof(T)-1;
11 for (int i = 0; i < sizeof(T); i++, --p) {
12 *buf++ = c2h[*p >> 4];
13 *buf++ = c2h[*p & 0x0F];
14 }
15 *buf = '\0';
16 printf("hex format displayed as %s\n", ptmp);
17
18 delete [] ptmp;
19 p = (unsigned char*)&v; p = p + sizeof(T)-1;
20 ptmp = buf = new char [sizeof(T)*8+1];
21 for (int i = 0; i < sizeof(T); i++, --p) {
22 for (int j = 0; j < 8; j++)
23 *buf++ = c2b[(*p >> (7-j)) & 0x1];
24 }
25 *buf = '\0';
26 printf("bin format displayed as %s\n", ptmp);
27 delete [] ptmp;
28 }
29