在串口通讯中,时常涉及到16进制字符串发送,需要将字符串转为16进制。
Example:string str = "07 0a 02 10 03 00 00 00 00 00"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int char2bits(char ch)
{
int bits = 0;
if (ch >= 'a' && ch <= 'z')
{
bits = ch - 'a' + 10;
}
else if (ch >= 'A' && ch <= 'Z')
{
bits = ch - 'A' + 10;
}
else if (ch >= '0' && ch <= '9')
{
bits = ch - '0';
}
else
{
bits = -1;
}
return bits;
}
int hex2bytes(const char *hex, char *bytes, int size)
{
int len = strlen(hex);
int nbytes = (len + 1) / 3;
if (nbytes > size)
{
return -1;
}
int n;
for (n = 0; n != nbytes; ++ n)
{
int lndx = n * 3;
int rndx = lndx + 1;
int lbits = char2bits(hex[lndx]);
int rbits = char2bits(hex[rndx]);
if (lbits == -1 || rbits == -1)
{
return -1;
}
bytes[n] = (lbits << 4) | rbits;
}
return nbytes;
}
int main(int argc, char* const argv[])
{
const char *hex = "07 0A 02 10 03 00 00 00 00 00";
char stream[10];
int nbytes = hex2bytes(hex, stream, 10);
if (nbytes != -1)
{
int i = 0;
for ( ; i < nbytes; ++ i)
{
printf("%02x ", stream[i]);
}
}
return 0;
}