1.c
#include<stdio.h>
#include<string.h>
#include"utils.h"
//20211102
int main() {
int p;
char bytearr[100];
printf("请输入一个整型数字\n");
scanf("%d",&p);
printf("把整型数转化为字节数组\n");
Int2ByteArr(p,bytearr);
// 给长度为奇数的字符串首位加一个0
int length = strlen(bytearr);
if (length % 2 != 0) {
memmove(bytearr + 1, bytearr, length + 1);
bytearr[0] = '0';
}
printf("字节数组为:");
printf("{%s}\n",bytearr);
char barr[100];
int h;
printf("请输入一个字节数组:");
scanf("%s",barr);
printf("把字节数组转化为整型数字:");
ByteArr2Int(barr,&h);
printf("%d\n",h);
}
utils.c
#include<stdio.h>
#include"utils.h"
#include<string.h>
//20211102
int Hex2Char(int fromi,char *toc) {
if(fromi>=0&&fromi<=9) {
*toc= fromi+'0';
} else if(fromi>=10&&fromi<=15) {
*toc = fromi+'A'-10;
} else {
printf("输入的16进制数据不正确!");
}
return 0;
}
int Char2Hex(char fromc,int *toi) {
if(fromc>='0'&& fromc<='9') {
*toi= fromc-'0';
} else if(fromc>='A'&& fromc<='F') {
*toi= fromc-'A'+10;
} else {
printf("输入的16进制字符不正确");
}
return 0;
}
int Int2ByteArr(int i,char *ba) {
int j;
int a;
int sum=0;
int k=i;
for(j=0;; j++) {
k=k/16;
if(k!=0)
sum++;
else
break;
}
for(j=sum; j>=0; j--) {
a = i%16;
Hex2Char(a,&ba[j]);
i=i/16;
}
ba[sum+1]='\0';
}
int ByteArr2Int(char *ba,int *i) {
int len;
int j;
int n=0;
*i=0;
len = strlen(ba);
for(j=0; j<len; j++) {
Char2Hex(ba[j],&n);
//printf("%d\n",n);
*i=(*i)*16+n;
}
}
utils.h
#ifndef _UTIL_H_
#define _UTIL_H_
//char Hex2Char(int i);
//int Char2Hex(char c);
int Hex2Char(int fromi,char * toc);
int Char2Hex(char fromc,int * toi);
int Bitstr2ByteArr(char * bs,char * ba);
int ByteArr2Bitstr(char * ba,char * bs);
int Int2ByteArr(int i,char * ba);
int ByteArr2Int(char * ba,int * i);
#endif
标签:字节,int,整数,char,数组,printf,include,bytearr,ba
From: https://www.cnblogs.com/yzy3655921/p/18228107