Converting an int to a 2 byte hex value in C

后端 未结 15 1409
不知归路
不知归路 2020-12-05 18:17

I need to convert an int to a 2 byte hex value to store in a char array, in C. How can I do this?

15条回答
  •  遥遥无期
    2020-12-05 19:11

    Here's a crude way of doing it. If we can't trust the encoding of ascii values to be consecutive, we just create a mapping of hex values in char. Probably can be optimized, tidied up, and made prettier. Also assumes we only look at capture the last 32bits == 4 hex chars.

    #include 
    #include 
    
    #define BUFLEN 5
    
    int main(int argc, char* argv[])
    {
      int n, i, cn;
      char c, buf[5];
      char hexmap[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','.'};
    
      for(i=0;i\n", argv[0]);
        return 1;
      }
      n = atoi(argv[1]);
      i = 0;
      printf("n: %d\n", n);
    
      for(i=0; i<4; i++)
      {
        cn = (n>>4*i) & 0xF;
        c  = (cn>15) ? hexmap[16] : hexmap[cn];
        printf("cn: %d, c: %c\n", cn, c);
    
        buf[3-i] = (cn>15) ? hexmap[16] : hexmap[cn];
      }
      buf[4] = '\0'; // null terminate it
    
      printf("buf: %s\n", buf);
      return 0;
    }
    

提交回复
热议问题