How to store a number in different variables

Hello,
I am working on this code where I need to store a 32 bit number but in two variables. For example:
1
2
3
4
5

int num = 16777215;
unsigned short MSB = 255;//the last 16 bits of num
unsigned short LSB = 65535;//the first 16 bits of num


However I am not sure how to do this. Num will be an input from an user via a text box. I have used logical AND and that doesn't work. Any help will be greatly appreciated.

Thanks In Advance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstdint>
#include <iostream>
#include <iomanip>

int main()
{
    constexpr std::uint32_t num_00_31 = 16777215 ;
    constexpr std::uint16_t num_00_15 = num_00_31 >> 16U ;
    constexpr std::uint16_t num_16_31 = num_00_31 ; // truncate

    std::cout << std::hex << "num_00_31: " << std::setw(8) << num_00_31 << '\n'
               << "num_00_15: " << std::setw(4) << num_00_15 << '\n'
               << "num_16_31: " << std::setw(8) << num_16_31 << '\n' ;
}
Try using a bit-wise and. I don't recall the syntax off the top of my head., but it should be something like this:
1
2
3
4
int num = 16777215;
unsigned short MSB, LSB;
MSB = num & 65535; //0000_0000_0000_0000_1111_1111_1111_1111
LSB = (num & 4294901760) / 65536; //1111_1111_1111_1111_0000_0000_0000_0000 

This should mask the 32 bit value, then assign the resulting masked value to the smaller variables. The division on the second effectively shifts the bits right 16 bits. This is necessary because when a larger number is assigned to a smaller variable, if I remember correctly, the right most digits are truncated. This division allows the correct value to be kept.
1
2
LSB = num & 0xFFFF;
MSB = (num >> 16) & 0xFFFF;
Last edited on
Another solution is using a union.
1
2
3
4
5
6
7
union split_un {
  int num;
  struct {
    short MSB;
    short LSB;
  } s;
} split;
Toum,
Thanks thats exactly what I was trying to do, I had the first part correct. Ok, now I want to know how put MSB and LSB together to get back num(16777215). I will have to display the values stored in LSB and MSB at some point.

Thanks In Advance
num = (MSB << 16) | LSB;
You could also use a union, but that's a dangerous solution because you have to take endianness into account.
Toum,
Thanks alot!!!However , I am not getting the original num when putting the LSB and MSB back together by hand. Code works but I was doing it by hand just to make sure that I am fully understanding what the code is doing. My take is that the MSB is left shifted 16 places in num and the LSB is OR with the LSB of num, which is 0's. Am I understanding this correctly?

Thanks Again!!!
Am I understanding this correctly?

Yes.

It's the same as doing
num = MSB * pow(2,16) + LSB;
Topic archived. No new replies allowed.