c++ 十六进制字符串存入文件实例

c++ 十六进制字符串存入文件:

方法一:

void writeToFile()
{
const char* str = "000000DD000000E00000015C000000E2";
FILE* file = fopen("test.txt", "wb");
assert(file);


size_t len = 0;
uint8_t* buf2 = ConvertToBinBuf(str, &len);
fwrite(buf2, 1, len, file);
free(buf2);
fclose(file);


printf(".......................\n");
}



size_t ConvertHexStrToInt(const char* hex_str, size_t length)
{
size_t sum = 0;
for (size_t i = 0; i < length; ++i)
{
int asc = (int)hex_str[i];
size_t r1 = (asc & 0x40) ? (asc & 0x0F) + 0x9 : (asc & 0x0F);
sum += (r1*pow(16, length - i - 1));
}
return sum;
}


uint8_t * ConvertToFileBuf(const char* hex_str, size_t *buf_size)
{
if (!hex_str)
{
*buf_size = 0;
return NULL;
}
//1.偶数个
size_t len = strlen(hex_str);
assert(!(len % 2));


*buf_size = len / 2;
uint8_t* buf = (uint8_t*)malloc(*buf_size);


for (size_t i = 0, j = 0; i < len; i += 2, ++j)
{
uint8_t value = (uint8_t)ConvertHexStrToInt(hex_str + i, 2);
buf[j] = value;
}
return buf;
}


方法二:


void writeToFile()
{
uint8_t buf[] =
{
0x00, 0x00, 0x00, 0xDD,
0x00, 0x00, 0x00, 0xE0,
0x00, 0x00, 0x01, 0x5C,
0x00, 0x00, 0x00, 0xE2
};


FILE* file = fopen("test.txt", "wb");
assert(file);
size_t len = 16;
fwrite(buf, 1, len, file);
fclose(file);
printf(".......................\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值