Converting an int to a 2 byte hex value in C

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

    This function works like a charm.

    void WORD2WBYTE(BYTE WBYTE[2], WORD Value) { 
        BYTE tmpByte[2]; 
        // Converts a value from word to word byte ----
        memcpy(tmpByte, (BYTE*) & Value, 2); 
        WBYTE[1] = tmpByte[0]; 
        WBYTE[0] = tmpByte[1]; 
    } 
    

    asumming the following:

    typedef unsigned char   BYTE; 
    typedef unsigned short  WORD;
    

    Example of use:

    we want to achieve this:

    integer = 92
    byte array in hex:
    a[0] = 0x00;
    a[1] = 0x5c;
    
    unsigned char _byteHex[2];
    WORD2WBYTE(_byteHex, 92);
    

提交回复
热议问题