How to split the character in a variable into half?

Anyone know how to write a program for the process stated on the title?
I'm trying to hard code some Modbus process for my project.

For example
Firstly, there will be a value of 9998 in decimal or 0x270E in hexadecimal
Next, i want to split the hexadecimal value of 0x270E into 0x27 and 0x0E (How to split???)
Lastly, i want to store the hexadecimal value of 0x27 and 0x0E into their own individual integer array.
Last edited on
if i have understood your question correctly, you can try the following:
(0x270E bit_and 0x00FF) will give you 0x000E
(0x270E bit_and 0xFF00) will give you 0x2700. divide this by 0x0100 or bit shift it right by the required amount. will give you 0x0027.
This should work if you simply create a union.
1
2
3
4
5
6
7
union Byte2{
    short full; //A short int is 2 bytes right??
    struct{
        char hi; //A character is a integer variable that takes up 1 byte
        char lo;
    }
}


http://www.cplusplus.com/doc/tutorial/other_data_types/
^How to use unions and structs

So... You create an instance of this union Byte2 var; as you would with any variable.
Then you assign it a value through either ("full") or ("hi" and "lo")...
 
var.full = 9998;

If you take a look at each character now you should find it split into 2 halves for you.
1
2
cout << "var.hi = " << var.hi << endl;
cout << "var.lo = " << var.lo << endl;

var.hi = 39
var.lo = 14
Last edited on
@SatsumaBenji


AFAIK you may not store data in one member of a union and access it through other data member of the same union. So your code is invalid according to the C++ Standard.
Not to mention it assumes that chars are 8 bits and shorts 2 byte, neither of which is guaranteed by the C++ standard.
Last edited on
The tutorial I linked for unions uses a struct of 2 short integers for 1 long integer, just as I have done here with a short integer and a character.
I do realise that the sizes of the variable type names is variable though accross systems, that could be a possible issue but surely there's simple ways around that, I know that there's a header somewhere which you can find the number of bits for each type correct?
@SatsumaBenji


One again. According to the C++ Standard

9.5 Unions [class.union]
1 In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ]
Topic archived. No new replies allowed.