C语言 str2bin 和 bin2str 实现
需求介绍
在编码或者调试过程中经常需要进行 字节码转换为 十六进制的字符串, 或者将 十六进制字符串 转换为 字节码的需求。
即: 字节码 (内存中存储的 01 串): 11111111
<------>
FF
Code
linux上调试通过。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>// Stringify binary data. Output buffer must be twice as big as input,
// because each byte takes 2 bytes in string representation
static void bin2str(char *to, const unsigned char *p, size_t len) {
static const char *hex = "0123456789abcdef";for (; len--; p++) {
*to++ = hex[p[0] >> 4];
*to++ = hex[p[0] & 0x0f];
}
*to = '\0';
}unsigned char char2val(const char source)
{
static const char * hex = "0123456789abcdef";
size_t index = 0;
int bLegalChar = 0;printf("source char =%c\n", source);
for ( index=0 ; index < 16; index++ )
{
if ( source == *(hex+index) )
{
bLegalChar = 1;
break;
}
}if ( !bLegalChar )
{
return -1;
}if ( '0' <= source && source <='9' )
{
return (unsigned char) (source - '0');
}
else if ( 'a' <= source && source <= 'f' )
{
return (unsigned char) (source - 'a') + 10 ;
}
else
{
return -1;
}
}// translate hex string to dest bin buff, which is len in length
static void str2bin(const char* source, unsigned char * dest, size_t len)
{
unsigned char byte_total = 0;
unsigned char byte_pre = 0;
unsigned char byte_post = 0;
const char * hex = 0;
size_t destIndex = 0;if ( strlen(source) % 2 == 1 )
{
printf("!! hex string len error!\n");
return;
}hex = source;
while ( *(hex) )
{
byte_pre = char2val(*hex);
hex++;byte_post = char2val(*hex);
hex++;byte_total = byte_pre << 4 ;
printf("byte_total pre << 4 = %d\n", byte_total);byte_total += byte_post;
printf("byte_pre=%d\n", byte_pre);
printf("byte_post=%d\n", byte_post);
printf("byte_total=%d\n", byte_total);if ( destIndex < len )
{
*(dest + destIndex) = byte_total;
destIndex++;
}
else
{
break;
}
}
}#define byte unsigned char
#define default_val (unsigned long)-1
void main()
{char binstr[1024] = {0};
char binstr2[1024] = {0};printf("aaaa\n");
byte buff[4] = {0};
byte buff2[4] = {0};
memset(buff, -1, 4);
bin2str(binstr, buff, 4);
printf("buff binstr =%s\n", binstr );
str2bin(binstr, buff2, 4);
bin2str(binstr2, buff2, 4);
printf("buff2 binstr2 =%s\n", binstr2);
printf("bbbb\n");
}
效果
代码演示了, 将一个 4 byte的空间, 初始化为 –1 , 即全部bit位置设置为 1, 然后将此空间转换为 hex字符串,
然后再将此hex字符串转换为 byte字节码空间。
最新文章
- HTML+CSS布局技巧及兼容问题【阅读季】
- 掌握 tar 命令让你秒变大牛
- hibernate的映射类型
- Wcf Client 异常和关闭的通用处理方法
- JAVA Socket:文件传输
- 9.cadence.封装1[原创]
- BestCoder Round #81 (div.1)A
- poj 3253 Fence Repair(优先队列+哈夫曼树)
- DedeCMS文章标题前增加所属栏目名称链接
- MarkDown基础使用教程-by sixleaves
- 第一个OC类、解析第一个OC程序
- outlook 当关闭时最小化到任务栏完美的解决方案
- easyui_datagrid 行内使用comobox的编码实现
- springboot+rediscluster
- MacbookPro下载word文件显示dms怎么办
- UVA1533-Moving Pegs(BFS+状态压缩)
- Linux:Day4(下) 用户及组管理
- onkeyup+onafterpaste 只能输入数字和小数点--转载
- hibernate配置二级缓存
- github不能访问、加载css、js解决办法