非printf形式打印各种数据类型的十六进制和二进制
一、源码实现
为了适配各种数据类型,且可以通过sizeof得到此类型的大小,所以这里采用模板形式开发。
以下是实现此功能的源码:
[cpp]
// 把十进制数(long型)分别以二进制和十六进制形式输出
template <typename T>
void displayHexBin(const T& v)
{
const unsigned char c2h[] = "0123456789ABCDEF";
const unsigned char c2b[] = "01";
unsigned char* p = (unsigned char*)&v;
char* buf = new char [sizeof(T)*2+1];
// 转为16进制
char* ptmp = buf;
p = p + sizeof(T)-1;
for (int i = 0; i < sizeof(T); i++, --p)
{
*buf++ = c2h[*p >> 4];
*buf++ = c2h[*p & 0x0F];
}
*buf = '\0';
printf("hex format displayed as %s\n", ptmp);
delete [] ptmp;
// 转为2进制
p = (unsigned char*)&v; p = p + sizeof(T)-1;
ptmp = buf = new char [sizeof(T)*8+1];
for (int i = 0; i < sizeof(T); i++, --p)
{
for (int j = 0; j < 8; j++)
*buf++ = c2b[(*p >> (7-j)) & 0x1];
}
*buf = '\0';
printf("bin format displayed as %s\n", ptmp);
delete [] ptmp;
}
// 把十进制数(long型)分别以二进制和十六进制形式输出
template <typename T>
void displayHexBin(const T& v)
{
const unsigned char c2h[] = "0123456789ABCDEF";
const unsigned char c2b[] = "01";
unsigned char* p = (unsigned char*)&v;
char* buf = new char [sizeof(T)*2+1];
// 转为16进制
char* ptmp = buf;
p = p + sizeof(T)-1;
for (int i = 0; i < sizeof(T); i++, --p)
{
*buf++ = c2h[*p >> 4];
*buf++ = c2h[*p & 0x0F];
}
*buf = '\0';
printf("hex format displayed as %s\n", ptmp);
delete [] ptmp;
// 转为2进制
p = (unsigned char*)&v; p = p + sizeof(T)-1;
ptmp = buf = new char [sizeof(T)*8+1];
for (int i = 0; i < sizeof(T); i++, --p)
{
for (int j = 0; j < 8; j++)
*buf++ = c2b[(*p >> (7-j)) & 0x1];
}
*buf = '\0';
printf("bin format displayed as %s\n", ptmp);
delete [] ptmp;
}
二、框图解释
以上代码分为两部分,一个是转为16进制;一部分是转为2进制。
1、以Int为例求它的16进制数
2、以Int为例求它的2 进制数
三、 数据测试
1、Int 转16 进制与2进制
[cpp]
// 测试四.1 Int 转16 进制与2进制
int dSourceOne = 2;
int dSourceTwo = -2;
displayHexBin(dSourceOne);
displayHexBin(dSourceTwo);
// 测试四.1 Int 转16 进制与2进制
int dSourceOne = 2;
int dSourceTwo = -2;
displayHexBin(dSourceOne);
displayHexBin(dSourceTwo);
结果:
2、float 转16进制与2 进制
[cpp]
// 测试四.2 double 转16 进制与2进制
float fSourceOne = 3.0;
float fSourceTwo = -2.0;
displayHexBin(fSourceOne);
displayHexBin(fSourceTwo);
printf("\n");
// 测试四.2 double 转16 进制与2进制
float fSourceOne = 3.0;
float fSourceTwo = -2.0;
displayHexBin(fSourceOne);
displayHexBin(fSourceTwo);
printf("\n");
float类型的二进制的存放方式请参考我的另一篇文章: 浮点型数据在内存中存储的表示[转载]
3、double 转16 进制与2进制
[cpp]
// 测试四.3 double 转16 进制与2进制
double dSourceOne = 2.0;
double dSourceTwo = -2.0;
displayHexBin(dSourceOne);
displayHexBin(dSourceTwo);
// 测试四.3 double 转16 进制与2进制
double dSourceOne = 2.0;
double dSourceTwo = -2.0;
displayHexBin(dSourceOne);
displayHexBin(dSourceTwo);
作者:chenyujing1234
补充:软件开发 , C++ ,