Spliting an hex into 2 hex values

前端 未结 3 2174
Happy的楠姐
Happy的楠姐 2020-12-22 06:51

I have a problem I have an Hexadecimal like 0x6002 and I have to split it into 0x60 and 0x02. how do I do that?

I progam in cp

3条回答
  •  青春惊慌失措
    2020-12-22 07:27

    Pointers are MUCH FASTER than shifts and require no processor math. You create your 2 byte variable and use Pointers to change each byte separately.

    Here is an example:

    uint16_t myInt; // 2 byte variable
    
    uint8_t *LowByte = (uint8_t*)myInt; // Point LowByte to the same memory address as
                  // myInt, but as a uint8 (1 byte) instead of a uint16 (2 bytes)
                  // Note that low bytes come first in memory
    
    
    uint8_t *HighByte = (uint8_t*)myInt + 1; // 1 byte offset from myInt start
    // which works the same way as:
    uint8_t *HighByte = LowByte + 1; // 1 byte offset from LowByte
    

    In some compilers the pointer syntax is a little different (such as Microsoft C++):

    uint16_t myInt; // 2 byte variable
    
    uint8_t *LowByte = (uint8_t*)&myInt; // Point LowByte to the same memory address as
                  // myInt, but as a uint8 (1 byte) instead of a uint16 (2 bytes)
                  // Note that low bytes come first in memory
    
    uint8_t *HighByte = (uint8_t*)&myInt + 1; // 1 byte offset from myInt start
    

    The * char in type definition indicates you are creating a pointer, not a variable. The pointer points to a memory address instead of it´s value. To write or read the value of the variable pointed to, you add * to the variable name.

    So, to manipulate the full 2 bytes together, or separately, here are some examples:

    myInt = 0x1234; // write 0x1234 to full int
    
    *LowByte = 0x34; // write 0x34 to low byte
    
    *HighByte = 0x12; // write 0x12 to high byte
    
    
    uint8_t x = *LowByte; // read low byte
    
    uint8_t y = *HighByte; // read high byte
    
    uint16_t z = myInt; // reads full int
    

提交回复
热议问题