After reading the question how to get bit by bit data from a integer value in c?, I see that if I want to look at each bit in an integer, I should right shift the integer and mask it. But I wonder is it possible to access each bit in the memory without such a complicated code? By using pointer
or something like that.

- 1
- 1

- 915
- 8
- 18
-
3No. To access individual bits, you have to shift and mask, just as the other question explains. If there were other ways to do so, they would have been provided as answers to that question. There's no magic trick that someone just decided to conceal from the other poster. The smallest amount of memory that can be accessed with a pointer is `sizeof(char)`, which is always at least one byte. – Ken White Nov 06 '14 at 02:56
-
There have historically been bit-addressable computers, but no modern computer allows it. – Hot Licks Nov 06 '14 at 03:50
-
Computers simply do not organize memory by individual bits. An address (a combination of lines that are on or off on the physical memory bus) refer to a specific *byte*. – Jonathon Reinhart Nov 06 '14 at 04:04
3 Answers
In C, bit wise operations, like shifting is one of the only ways to manipulate variables on the bit level. Its expressions can be somewhat "ugly" at first glance but like everything through practice, will soon be easy to understand.
Just keep at it.
Here's a great article for your interest: A bit of fun: fun with bits

- 191
- 11
It is possible to do it without shifting and masking, but it's hardly less "complicated" to do so:
#include <stdio.h>
#include <stdbool.h>
unsigned int ui_pow(unsigned int base, unsigned int exponent)
{
unsigned int result = 1;
for ( unsigned int i = 1; i <= exponent; ++i ) {
result *= base;
}
return result;
}
bool bit_is_set_one(unsigned int n, unsigned int bit)
{
return (n >> bit) & 1;
}
bool bit_is_set_two(unsigned int n, unsigned int bit)
{
return (n / ui_pow(2, bit)) % 2;
}
int main(void)
{
bool all_equal = true;
for ( unsigned int i = 0; i < 65535; ++i ) {
for ( unsigned int j = 0; j < 16; ++j ) {
if ( bit_is_set_one(i, j) != bit_is_set_two(i, j) ) {
all_equal = false;
}
}
}
printf("Methods%s give equal results.\n", all_equal ? "" : " do not");
return 0;
}
which outputs:
paul@thoth:~/src/sandbox$ ./altshift
Methods give equal results.
paul@thoth:~/src/sandbox$

- 25,242
- 5
- 48
- 56
If you know the bit location, you can do a bit mask without doing the shift. For example: (i & 0x02) You'll get 0x02 if the 2nd bit from right is a 1, or 0x00 if the 2nd bit is a 0. Usually a macro is used: #define BitMask(i) (1 << (i)) For a constant i, the shift will be handle in compilation stage, and it wont show up in final binaries.

- 74
- 5