Hello, I am trying to make a class which can represent an integral or floating point variable of any size (in bytes), which contains its own operators and ways of casting between the different types. To store the value, I am using a vector of chars because they are 1-byte large. I am currently a bit confused as to how I would represent say, a short as two chars. I did think that I could split the short into two half's and store the both half's into different chars, for example 13412 (00110100 01100100): Char0 = 52 (00110100), Char1 = 100 (01100100) but I cant figure out how to implement this in C++, and then reassemble them again when their needed as a short. If someone could give me some hints I would be very grateful. Thank you.
Depending on endianness and that your implementation represents a short as a word (rare that it wouldn't), you could pull out each octet with a bitwise operation:
1 2 3 4
short w = 13412;
int hiByte = (w >> 8) & 0xff;
int loByte = w & 0xff;
Casting your output with int will get you 52 and 100 respectively. From here you can place them in your array. A separate function could easily put them back together when called.
I might not be fully understanding what you are trying to achieve, so get back if not.
Okay, I understand thank you :) Just to extend my question somewhat, how would I go about adding two shorts represented as two chars? Like for example:
(loByte1 and hiByte1) + (loByte2 and hiByte2) = (loByte3 and hiByte3)
Well, there are a number of ways that come to mind. You said you are throwing the bytes into an array, but how are they organized from there? If you are comfortable with Object Oriented styles, this could work well with an overloaded operator+.
If not, make a function that returns a short, but takes two char arguments, splitBytes() does the work from my first reply: