欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

10进制/16进制字符串和数字转换

程序员文章站 2024-03-17 12:59:52
...
#include <stdio.h>
#include <stdlib.h>

int main()
{
  //1.将10进制和16进制字符串转换成数字
  char a[] = "100";
  char c[] = "0xff";
  printf("a = %ld\n", strtol(a, NULL, 10)); //100
  printf("c = %ld\n", strtol(c, NULL, 16)); //255

  //2.将数字转换成16进制字符串
  int rreg = 9;
  char reg[16] = {0};
  char cmd[64] = {0};

  sprintf(reg,"0x%02x", rreg);//02x:如果小于9则补0;大于9则实际输出;2x则是实际输出(不补0)
  sprintf(cmd,"echo \"%s\" > /dev/led", reg);
  printf("cmd = %s\n",cmd);
  return 0;
}