数据转换-位串字节数组
数据转换-位串字节数组
utils.h
#ifndef UTILS_H
#define UTILS_H
int BitStr2ByteArr(char *bs,char *ba,int lbs);
int ByteArr2BitStr(char *ba,char *bs,int lba);
#endif
utils.c
#include<stdio.h>
#include"utils.h"
#include<string.h>
int Hex2Char(int f,char *t)
{
if(f>=0&&f<=9)
{
*t= f+'0';
}
else if(f>=10&&f<=15)
{
*t = f+'A'-10;
}
else
{
printf("input error!");
}
return 0;
}
int Char2Hex(char f,int *t1)
{
if(f>='0'&& f<='9')
{
*t1= f-'0';
}
else if(f>='A'&& f<='F')
{
*t1= f-'A'+10;
}
else
{
printf("input error!");
}
return 0;
}
int ByteArr2BitStr(char *ba,char *bs,int lba)
{
int i,j;
int k;
int a;
for(j=0;j<lba;j++)
{
Char2Hex(ba[j],&a);
for(i=0;i<4;i++)
{
bs[3*(j+1)-i+j] = a%2+'0';
a=a/2;
}
}
bs[4*lba]='\0';
}
int BitStr2ByteArr(char *bs,char *ba,int lbs)
{
char string[100];
int k;
int i;
int j;
int sum=0;
if(lbs%4==1)
{
strcpy(string,"000");
strcat(string,bs);
k=lbs/4+1;
}
else if(lbs%4==2)
{
strcpy(string,"00");
strcat(string,bs);
k=lbs/4+1;
}
else if(lbs%4==3)
{
strcpy(string,"0");;
strcat(string,bs);
k=lbs/4+1;
}
else
{
k=lbs/4;
strcpy(string,bs);
}
for(i=0;i<k;i++)
{
for(j=0;j<4;j++)
{
sum=sum*2;
sum=sum+(string[4*i+j]-'0');
}
Hex2Char(sum,&ba[i]);
sum=0;
}
ba[i]='\0';
}
test.c
#include<stdio.h>
#include"utils.h"
int main(){
char bytes[100];
char bitss[100];
int len,len1;
printf("Input(byte):");
scanf("%s",bytes);
printf("Input(len):");
scanf("%d",&len);
ByteArr2BitStr(bytes,bitss,len);
printf("bit:\n");
printf("%s\n",bitss);
len1= strlen(bitss);
printf("len=%d\n",len1);
char bytes_1[100];
char bitss_1[100];
int len_1,len2;
printf("Input(01):");
scanf("%s",bitss_1);
printf("Input(len):");
scanf("%d",&len_1);
BitStr2ByteArr(bitss_1,bytes_1,len_1);
printf("byte:\n");
printf("%s\n",bytes_1);
len2= strlen(bytes_1);
printf("len=%d\n",len2);
return 0;
}