Spliting an hex into 2 hex values

前端 未结 3 2168
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:07

    You can use masking to extract the low byte and a shift to extract the high byte:

    uint16_t a = 0x6002;
    uint8_t a0 = a & 0xff;  // a0 = 0x02
    uint8_t a1 = a >> 8;    // a1 = 0x60
    

    Note that the & 0xff is not strictly necessary for a narrowing unsigned conversion such as that above, but there are other cases where it might be necessary (e.g. when signed conversion is involved, or when the destination type is wider than 8 bits), so I'll leave it in for illustrative purposes.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-22 07:28
    uint16_t port = 0x6002;
    uint8_t high = (port >> 8) & 0xFF;
    uint8_t low = port & 0xFF;
    
    0 讨论(0)
提交回复
热议问题