Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 bits size variable

Tags:

c++

size

bit

I need to define a struct which has data members of size 2 bits and 6 bits. Should I use char type for each member?Or ,in order not to waste a memory,can I use something like :2\ :6 notation? how can I do that? Can I define a typedef for 2 or 6 bits type?

like image 244
Yakov Avatar asked Jan 30 '13 09:01

Yakov


People also ask

Is short always 2 bytes?

The size of the short type is 2 bytes (16 bits) and, accordingly, it allows expressing the range of values equal to 2 to the power 16: 2^16 = 65 536.

Why int is 2 or 4 bytes?

In any programming language, size of a data type is means how many binary bits are used to store an instance of that type. So, size of int data type is 2 bytes means that the compiler uses two bytes to store a int value.


2 Answers

You can use something like:

typedef struct {
    unsigned char SixBits:6;
    unsigned char TwoBits:2;
} tEightBits;

and then use:

tEightBits eight;
eight.SixBits = 31;
eight.TwoBits = 3;

But, to be honest, unless you're having to comply with packed data external to your application, or you're in a very memory constrained situation, this sort of memory saving is not usually worth it. You'll find your code is a lot faster if it's not having to pack and unpack data all the time with bitwise and bitshift operations.


Also keep in mind that use of any type other than _Bool, signed int or unsigned int is an issue for the implementation. Specifically, unsigned char may not work everywhere.

like image 82
paxdiablo Avatar answered Sep 25 '22 18:09

paxdiablo


It's probably best to use uint8_t for something like this. And yes, use bit fields:

struct tiny_fields
{
  uint8_t twobits : 2;
  uint8_t sixbits : 6;
}

I don't think you can be sure that the compiler will pack this into a single byte, though. Also, you can't know how the bits are ordered, within the byte(s) that values of the the struct type occupies. It's often better to use explicit masks, if you want more control.

like image 23
unwind Avatar answered Sep 26 '22 18:09

unwind