Daniel D
Daniel D

Reputation: 3

How to write and read bytes from unsigned variable

Here is what I'm trying to do:

I have two integers

int a = 0; // can be 0 or 1
int b = 3; // can be 0, 1, 2 or 3

Also I want to have

unsigned short c

to store that variables inside it.

For example, if I would store a inside c it will be looking like this:

00000000
^ here is a

Then I need to store b inside c. And it should look like following:

011000000
 ^^ here is b.

Also I would like to read that numbers back after writing them. How can I do this?

Thanks for your suggestions.

Upvotes: 0

Views: 350

Answers (2)

MooseBoys
MooseBoys

Reputation: 6793

You can accomplish this with C++ Bit Fields:

struct MyBitfield
{
    unsigned short a : 1;
    unsigned short b : 2;
};
MyBitfield c;
c.a = // 0 or 1
c.b = // 0 or 1 or 2 or 3

Upvotes: 0

john
john

Reputation: 87962

Assuming those are binary representations of the numbers and assuming that you really meant to have five zeros to the right of b

01100000
 ^^ here is b

(the way you have it a and b overlap)

Then this is how to do it

// write a to c
c &= ~(1 << 7);
c |= a << 7;

// write b to c
c &= ~(3 << 5);
c |= b << 5;

// read a from c
a = (c >> 7)&1;

// read b from c
b = (c >> 5)&3;

Upvotes: 3

Related Questions