Converting an int to a 2 byte hex value in C

后端 未结 15 1407
不知归路
不知归路 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:13

    Using Vicky's answer above

    typedef unsigned    long    ulong;
    typedef unsigned    char    uchar;
    
    #define TO_HEX(i)   (i <= 9 ? '0' + i : 'A' - 10 + i)
    #define max_strhex  (sizeof(ulong)*2)
    
    public uchar
    *mStrhex(uchar *p, ulong w, ulong n)
    {
        ulong i = 0xF;                                  // index
        ulong mask  = i << (((sizeof(ulong)*2)-1)*4);   // max mask (32 bit ulong mask = 0xF0000000, 16 bit ulong mask = 0xF000)
        ulong shift = (w*4);                            // set up shift to isolate the highest nibble
        if(!w || w > max_strhex)                        // no bold params
            return p;                                   // do nothing for the rebel
        mask  = mask >> (max_strhex-w)*4;               // setup mask to extract hex nibbles
        for(i = 0; i < w; i++){                         // loop and add w nibbles
            shift = shift - 4;                          // hint: start mask for four bit hex is 0xF000, shift is 32, mask >> 32 is 0x0000, mask >> 28 is 0x000F.
            *p++ = TO_HEX(((n & mask) >> shift));       // isolate digit and make hex
            mask = mask >> 4;                           //
            *p = '\0';                                  // be nice to silly people
        }                                               //
        return p;                                       // point to null, allow concatenation
    }
    

提交回复
热议问题