How to store 4bit data types in a file

Started by
3 comments, last by Michael85033 22 years, 6 months ago
How do I get a data type with 4 bits of size? I need it for Windows Bitmap (DIB) manipulation. If the Bitmap is in 4 bit per pixel format, (that makes for a palette of 16 colors) I need to get a pointer to the bitmap bits which is 4 bits wide. But the smallest I can get is 8 bits (by using an unsigned char). Simply trimming the value to a max of 0xFF won´t cut it, because the type pointed to by my surface pointer is still 8 bits wide and the next 4 bits are filled with zeroes. How would you do it?
Advertisement
I''m not exactly sure what you''re trying to do, but you can''t access 4 bits directly. You have to get 8 bits then mask off the unwanted part.

lower 4 bits = 8bits & 0xF
upper 4 bits = (8bits & 0xF0)>>4

That''s very quick off the top of my head. Check to make sure it works ok.
typedef struct FOURBITS
{
char data :4;
}FOURBITS;

struct FOURBITS data;

then to access

data.data = 15;

that should work, been a while since ive used bit fields
First off, thank you for your replies!

Thrump: I had already thought of something like this, but I hadn´t yet grasped bitwise operations in C that well. But your tip made it all go *click* inside my head and it works now as intended!

I´ve come up with a bitfield packed in a struct as well, but I couldn´t get a pointer to the wrapped bitfield in it (only to the structure as a whole, which wasn´t of any use).
First off, thank you for your replies!

Thrump: I had already thought of something like this, but I hadn´t yet grasped bitwise operations in C that well. But your tip made it all go *click* inside my head and it works now as intended!

I´ve come up with a bitfield packed in a struct as well, but I couldn´t get a pointer to the wrapped bitfield in it (only to the structure as a whole, which wasn´t of any use).

This topic is closed to new replies.

Advertisement