# Thread: bits like int x:4

1. ## bits like int x:4

hi

i want to create an unsigned integer array with 10 members each of them is 4 bit.
for example
unsigned int x:4; create an int element with 4 bit ,so 0 to 15 can be assgined t ox

how can i create an array like i explain above

2. As far as I know, you cannot create your own sized datatypes. What you could do is use bitshifting and masking to store several of your 4bitIntegers in one larger datatype.

ie: a char is 8bit (which means you can store 2 4bitInts in it)

To get the first int:

((CharVar & 0xF0) >> 4)

To get the second int4 (4-bit int):

(CharVar & 0x0F)

To store the first int4:

CharVar = (CharVar & 0x0F) | ((Int4 << 4) & 0xF0)

To store the second int4:

CharVar = (CharVar & 0xF0) | (Int4 & 0x0F)

3. The format of the code that you are using looks a bit like bit fields.
EG:
Code:
struct foo
{
unsigned int x     : 1;
unsigned int y     : 4;
};
..but this doesn't work with arrays. What is it that you need to do exactly?

4. foniks munkee said that
"..but this doesn't work with arrays. What is it that you need to do exactly?"

for example 10000 students at a university . i want to manipulate their grades . a student can take 5 lesson ,and each lesson have 2 midterms,2quiz and a final. the range for mid quiz and finals are 0-100 ,so if i use int for hold grades it wastes the memory so much . For 6 bit is enough to hold mid grades...

i think it is more clear

5. >so if i use int for hold grades it wastes the memory so much

For an application like you're working on, I wouldn't care about memory. I guess you're working on a PC which has I guess, lots of memory.

Instead of an unsigned int, you could use an unsigned char.

6. Well, if you have to store the students name with their score you could use an array of structures and use bit fields to store the scores.