#include <ctype.h>
#include <stdio.h>
#include <stdint.h>
void strToHex(uint8_t *pbDest, const char *pbSrc, int nLen)
{
uint8_t s1,s2;
int i = 0;
if(nLen % 2){
s1 = toupper(pbSrc[i ++]) - 0x30;
if(s1 > 9){
s1 -= 7;
}
pbDest[0] = s1;
}
while(i < nLen){
s1 = toupper(pbSrc[i ++]) - 0x30;
if(s1 > 9){
s1 -= 7;
}
s2 = toupper(pbSrc[i ++]) - 0x30;
if(s2 > 9){
s2 -= 7;
}
pbDest[(i - 1) / 2] = (s1 << 4) | s2;
}
}
void hexToStr(char *pbDest, uint8_t *pbSrc, int nLen)
{
char ddl,ddh;
int i;
for (i=0; i<nLen; i++){
ddh = 48 + (pbSrc[i] >> 4);
ddl = 48 + (pbSrc[i] & 0xF);
if (ddh > 57) ddh = ddh + 7;
if (ddl > 57) ddl = ddl + 7;
pbDest[i * 2] = ddh;
pbDest[i * 2 + 1] = ddl;
}
pbDest[nLen*2] = '\0';
}
int main(void){
const char *pc = "12345678";
char c[32];
uint8_t ic[8];
int i;
strToHex(ic, pc, 8);
for(i = 0; i < 8; ++ i){
printf("%x\n", ic[i]);
}
hexToStr(c, ic, 8);
printf("%s\n", c);
}
2020.11.2
可直接使用strtol函数,在stdlib.h中