简体   繁体   中英

Spliting an hex into 2 hex values

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 cpp and have to communicate with a network port. For that I have an address which I have to split in the middle my issue is that I store the hex in a Uint8 wich converts the number to a decimal. how can i solve my problem?

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 (eg when signed conversion is involved, or when the destination type is wider than 8 bits), so I'll leave it in for illustrative purposes.

uint16_t port = 0x6002;
uint8_t high = (port >> 8) & 0xFF;
uint8_t low = port & 0xFF;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM