unused memory using 32 bit integer in C
سؤال
I have the folowing struct of integers (32 bit environment):
struct rgb {
int r;
int g;
int b;
};
Am I correct in saying that, since rgb component values (0-255) only require 8-bits(1 byte) to be represented, I am only using 1 byte of memory and leaving 3 bytes unused for each component?
Also, if I instead did the following:
struct rgb{
unsigned int r:8;
unsigned int g:8;
unsigned int b:8;
};
Assuming that what I said above is correct, would using this new struct reduce the number of unused bytes to 1?
المحلول
I would use unsigned char
, which is exactly what you need. Like
#ifndef BYTE
#define BYTE unsigned char
#endif
struct rgb
{
BYTE r;
BYTE g;
BYTE b;
};
But to answer your question - yes, it does reduce the number of bytes to 1 for each field.
Anyway, the struct will probably be with size of 4B, because of the alignment (but these are details and it's completely platform specific) removed, thanks to @JimBuck's comment
نصائح أخرى
Yes that is correct. The second solution will essentially break down the struct to a single int with 8bits for each member.
#include "stdio.h"
struct rgb{
unsigned int r:8;
unsigned int g:8;
unsigned int b:8;
};
int main(void) {
printf("Size of RGB: %d", sizeof(struct rgb));
return 0;
}
This will output: "Size of RGB: 4". But as others have suggested it will be best to use a datatype that comes with 8bits, ergo: unsigned char
.
Integers are 32 bit -> 4 bytes. I would use unsigned char instead, which is only 1 byte containing values 0-255.
Using typedef to define a new name for the type makes it more convenient to use.
typedef unsigned char t_byte;
struct rgb {
t_byte r;
t_byte g;
t_byte b;
};
Unsigned int is still the same size, you want unsigned char
struct rgb{
unsigned char r;
unsigned char g;
unsigned char b;
};
However, you should remember that the standard does not enforce they are not larger -- they may be bigger anyway. You might need to use a packed pragma to get exactly the alignment you want.
You could also use unsigned char rgb[3]
In the first sample you are allocating 4 bytes per color component. For 8 bit color you should allocate just a single byte by using unsigned char. No need for bitfields here.
Note that you have defined a 24 bit pixel here. You may need to add padding if you are using 32 bit pixels.