场景:
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; +
本文介绍了在C/C++中如何输出内存数据的二进制和十六进制字符串形式,特别是在文件读取或内存分析时的场景。由于标准printf函数不支持直接显示二进制,且%x格式化输出限制为8字节,对于超过8字节的数据,需要采用其他方法来实现。
订阅专栏 解锁全文
6541

被折叠的 条评论
为什么被折叠?



