首页 > 代码库 > [C/C++]_[输出内存数据的二进制和十六进制的字符串表示]

[C/C++]_[输出内存数据的二进制和十六进制的字符串表示]


场景:

1. 在读取文件或内存时,有时候需要输出那段内存的十六或二进制表示进行分析。

2. 标准的printf没有显示二进制的,而%x显示有最大上限,就是8字节,超过8字节就不行了。


test_binary_hex.cpp

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
#include <iostream>

std::string ToBinaryString(const uint8_t* buf,int len)
{
	int output_len = len*8;
	std::string output;
	const char* m[] = {"0","1"};

	for(int i = output_len - 1,j = 0; i >=0 ; --i,++j)
	{
		output.append(m[((uint8_t)buf[j/8] >> (i % 8)) & 0x01],1);
	}
	return output;
}

std::string ToHexString(const uint8_t* buf,int len,std::string tok = "")
{
	std::string output;
	char temp[8];
	for (int i = 0; i < len; ++i)
	{
		sprintf(temp,"0x%.2x",(uint8_t)buf[i]);
		output.append(temp,4);
		output.append(tok);
	}

	return output;
}

int main(int argc, char const *argv[])
{
	printf("0x%.2x\n",1);

	uint8_t buf[] = {0x80,0x0f,0x51,0xEE,0xA7};
	std::string output = ToBinaryString(buf,2);
	std::string output_hex = ToHexString(buf,2,":");
	std::cout << output << std::endl;
	std::cout << output_hex << std::endl;
	assert(!strcmp(output.c_str(),"1000000000001111"));
	
	output = ToBinaryString(buf,3);
	std::cout << output << std::endl;
	assert(!strcmp(output.c_str(),"100000000000111101010001"));
	

	output = ToBinaryString(buf,4);
	assert(!strcmp(output.c_str(),"10000000000011110101000111101110"));
	std::cout << output << std::endl;

	output = ToBinaryString(buf,5);
	assert(!strcmp(output.c_str(),"1000000000001111010100011110111010100111"));
	std::cout << output << std::endl;

	return 0;
}

输出:

0x01
1000000000001111
0x80:0x0f:
100000000000111101010001
10000000000011110101000111101110
1000000000001111010100011110111010100111