最近有个功能需要用到颜色值的十进制值和十六进制字符串互转,查了一些资料实现后记录下。
上代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
int initial;
char hex[16];
char *str;
int decimal;
initial = 65535;
printf(" =========== test 1 =========== \n");
memset(&hex, 0, sizeof(hex));
sprintf(hex, "%08x", initial);
printf("hex = %s\n", hex);
decimal = strtol(&hex[0], NULL, 16);
printf("decimal = %d\n", decimal);
printf(" =========== test 2 =========== \n");
memset(&hex, 0, sizeof(hex));
sprintf(hex, "#%08x", 65535);
printf("hex = %s\n", hex);
decimal = strtol(&hex[1], NULL, 16);
printf("decimal = %d\n", decimal);
printf(" =========== test 3 =========== \n");
memset(&hex, 0, sizeof(hex));
sprintf(hex, "%08x@@@", 65535);
printf("hex = %s\n", hex);
decimal = strtol(&hex[0], &str, 16);
printf("decimal = %d\n", decimal);
printf("decimal = %s\n", str);
return 0;
}
测试一、二、三实现的都是将十进制转换成十六进制字符串然后再转换成十进制的过程。
strtol函数解释:
- *nptr:传入是要转换的字符串数值的起始指针。
- **endptr:传入一个char * 的指针,用于接收第一个不符合转换条件的字符指针。
- base:要被转换的数值的进制类型。