Can you tell me the best way to reserve for example 1000 bits from memory in C? I'm doing a program and i need to manage flags (values =0 or =1). What is the most efficient way to do that? I was thinking in reserve the space needed and control the flags (bits) using masks. Thank you
Asked
Active
Viewed 1,798 times
0
-
1Which is more important: minimizing the amount of space this takes up, or minimizing the time it takes to access an individual value? – robert Jun 02 '12 at 19:47
-
I would be surprised if toggling flags would be a bottle neck. Usually its the process that the flags correspond to? – Mikhail Jun 02 '12 at 23:39
3 Answers
3
The least amount of memory you can access/address in C is a byte which is of CHAR_BIT
bits width (which is guranteed to be at least 8 bits long). So, if you are looking for a packed structure you could use ceil(1000/8)
bytes.
You may want to take a look at this SO question for bit manipulation details.

Community
- 1
- 1

dirkgently
- 108,024
- 16
- 131
- 187
-
+1: This solution minimize memory usage. Since the OP didn't specify what "efficient" means, both this technique and Ouah's answer the question. – wallyk Jun 02 '12 at 19:59
2
You can use the bool
type:
#include <stdbool.h> // for bool
#include <stdlib.h> // for malloc
#define N 1000
bool *b = malloc(N * sizeof *b);
// for example to set the 42th element to 1
b[41] = 1;

ouah
- 142,963
- 15
- 272
- 331
-
1+1: This solution minimizes access time. No need to use `malloc()` though. It could be a non-heap variable, either local to a function or global. – wallyk Jun 02 '12 at 19:58
0
something like?
struct bitf
{
unsigned char b:1;
};
struct bitf[1000];
if you won't to use bitmask the max size is the max size of a variable on your computer. Error trying to define a 1,024-bit (128 Byte) Bit Field
or for min memory:
#include <stdio.h>
int main(void)
{
struct bitf
{
unsigned char a:1;
unsigned char b:1;
unsigned char c:1;
unsigned char d:1;
unsigned char e:1;
unsigned char f:1;
unsigned char g:1;
unsigned char h:1;
};
struct bitf number[125];
number[100].a = 1;
number[110].h =1;
printf("size: %d a:%d h:%d\n",sizeof(number), number[100].a ==0, number[110].h ==1);
return 0;
}
output:
size: 125 a:0 h:1