十六进制转字符串,字符串转16进制

字符串转16进制,十六进制转字符串

#include 
#include 
#include 
#include 

static void str_to_hex(char *ptr, unsigned char *buf, int len)
{
    for (int i = 0; i < len; i++)
    {
        sprintf(ptr, "%02x", buf[i]);
        ptr += 2;
    }
}

int hexcharToInt(char c)
{
	if (c >= '0' && c <= '9') return (c - '0');
	if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
	if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
	return 0;
}

void hex2bin(unsigned char *bin, char *hex) {
	int i = 0;
	for (i = 0; i < strlen(hex); i += 2) {
		bin[i / 2] = (char)((hexcharToInt(hex[i]) << 4)
			| hexcharToInt(hex[i + 1]));
	}
}

void main()
{
    unsigned char buf[] = "220";
    int len = strlen(buf);
    printf("字符串长度 = %d\n", len);

    char *ptr = malloc(len * 2);
    str_to_hex(ptr, buf, len);
    printf("hex字符串 ptr= %s\n", ptr);

    char *string = malloc(len);
    hex2bin(string, ptr);

    printf("字符串 string= %s\n", string);

    return;
}

测试结果

在这里插入图片描述

数字转为占俩字节的十六进制数

    char cmd[800] = "SEND_SMS,1,20210507175954-1-0-0-0-0-e682a8e69c89e4b880e4b8aae9a284e4b9a0e4bbbbe58aa1e380903035e69c883037e697a52028e5b08fe5ada6e8afade696872920e9a284e4b9a0e4bbbbe58aa1e38091efbc8ce8afb7e59ca8e5aeb6e995bfe7abafe69fa5e79c8b";

    int cmdlen = strlen(cmd);
    printf("字符串长度 = %u\n", cmdlen);
    char con[100] = {0};
    sprintf(con, "%04X", cmdlen);
    printf("数字转为占俩字节的十六进制数 = %s\n", con);

测试结果

在这里插入图片描述

十六进制值转数字

#include 
#include 

static int get_index_of_signs(unsigned char ch)
{
    if (ch >= '0' && ch <= '9')
    {
        return (ch - '0');
    }
    if (ch >= 'A' && ch <= 'F')
    {
        return (ch - 'A' + 10);
    }
    if (ch >= 'a' && ch <= 'f')
    {
        return (ch - 'a' + 10);
    }
    return (-1);
}

static int hex_to_int(unsigned char *source)
{
    int sum = 0;
    int t = 1;
    int i, len;
    len = strlen(source);
    for (i = len - 1; i >= 0; i--)
    {
        sum += t * get_index_of_signs(*(source + i));
        t *= 16;
    }

    return (sum);
}

int main()
{
    unsigned char *source = "000a";
    printf("hextoint = %d\n", hex_to_int(source));

    printf("%d\n", (128 & 128) != 0);
    return 0;
}

测试结果

在这里插入图片描述

你可能感兴趣的:(C语言,物联网,嵌入式)