set bin field in an array based on offset and length - c

I want to develop a function in C that set a binary field in array starting from a given offset and finish with a given length.
For example, my binary array is:
01101011 10010101 11001011 11010001 11000101 00101011
the buffer used for set:
10011001 01011011 10100010
So if the offset = 5 and the length = 7, the result will be
we will set the 7 first bit from the set buffer (1001100) in the binary buffer starting from the offset 5:
01101100 11000101 11001011 11010001 11000101 00101011
^ ^
| |__End of set field (len=7)
offset=5
Are there predefined algorithms for that? using bitwise operators?

Given char * arrays, you can easily implement operators set and get to set and retrieve, respectively, the i-th bit:
void set(char *a, int position, int value) {
int byte = position >> 3;
int bit = 1 << (position & 0x07); // 00000001b to 10000000b
a[byte] = value ?
a[byte] | bit : // on
a[byte] & ~bit; // off
}
int get(char *a, int position) {
return a[position>>3] & (1 << (position&0x07)) ? 1 : 0;
}
This can be made slightly faster with compiler intrinsics to get both division and modulus at the same time, and there is probably some bitwise trick to avoid branching in 'set' - but hopefully this code communicates the gist of the operation.
Implementing your desired function is essentially an extension of the code in my set function, where instead of only touching one bit, you continue until you run out of bits to modify, starting at the indicated offset.
Edit: adding a bitwise trick from this answer to remove branching from set:
void set(char *a, int position, int value) {
int byte = position >> 3;
int offset = position & 0x07);
a[byte] = (a[byte] & ~(1<<offset)) | (value<<offset);
}
Note that this version requires value to be either 0 or 1; the previous version would work with any false or true (=zero vs. non-zero) value.

Related

Swapping bits in an integer in C, can you explain this function to me?

I want to write a function that receives an unsigned char and swaps between bit 2 and bit 4 and returns the new number.
I am not allowed to use if statement.
So I found this function, among other functions, but this was the most simple one to understand (or try to understand).
All other functions involve XOR which I don't really understand to be honest.
unsigned char SwapBits(unsigned char num)
{
unsigned char mask2 = ( num & 0x04 ) << 2;
unsigned char mask4 = ( num & 0x10 ) >> 2;
unsigned char mask = mask3 | mask5 ;
return ( num & 0xeb ) | mask;
}
Can someone explain me what happens here and most important, why?
Why AND is required here and why with hex address?
Why should I AND with 0xeb (255)? I know that's the range of char but why should I do that.
In short,
I know how to read codes. I understand this code, but I don't understand the purpose of each line.
Thanks.
First, the usual convention is that bits are numbered starting from 0 for the least significant bit and counting up. In this case, you have an 8-bit value, so the bits go from 0 on the right up to 7 on the left.
The function you posted still isn't quite right, but I think I see where you (it) was going with it. Here are the steps it's doing:
Pull out bit 2 (which is 3rd from the right) using a mask
Pull out bit 4 (which is 5th from the right) using a mask
Shift bit 2 left 2 positions so it's now in bit 4's original position
Shift bit 4 right 2 positions so it's now in bit 2's original position
Join these two bits together into one value that is now bits 2 and 4 swapped
Mask out (erase using &) only bits 2 and 4 from the original value
Join in (insert using |) the new swapped bits 2 and 4 to complete the transformation
I have rewritten the function to show each step one at a time to help make it clearer. In the original function or other examples you find, you'll see many of these steps all happen together in the same statement.
unsigned char SwapBits(unsigned char num)
{
// preserve only bit 2
unsigned char bit2 = num & 0x04;
// preserve only bit 4
unsigned char bit4 = num & 0x10;
// move bit 2 left to bit 4 position
unsigned char bit2_moved = bit2 << 2;
// move bit 4 right to bit 2 position
unsigned char bit4_moved = bit4 >> 2;
// put the two moved bits together into one swapped value
unsigned char swapped_bits = bit2_moved | bit4_moved;
// clear bits 2 and 4 from the original value
unsigned char num_with_swapped_bits_cleared = num & ~0x14;
// put swapped bits back into the original value to complete the swap
return num_with_swapped_bits_cleared | swapped_bits;
}
The second to last step num & ~0x14 probably needs some explanation. Since we want to save all the original bits except for bits 2 and 4, we mask out (erase) only the bits we're changing and leave all the others alone. The bits we want to erase are in positions 2 and 4, which are the 1s in the mask 0x14. So we do a complement (~) on 0x14 to turn it into all 1s everywhere except for 0s in bits 2 and 4. Then we AND this value with the original number, which has the effect of changing bits 2 and 4 to 0 while leaving all the others alone. This allows us to OR in the new swapped bits as the final step to complete the process.
You have to read about binary representation of number
unsigned char SwapBits(unsigned char num)
{
// let say that [num] = 46, it means that is is represented 0b00101110
unsigned char mask2 = ( num & 0x04 ) << 2;
// now, another byte named mask2 will be equal to:
// 0b00101110 num
// 0b00000100 0x04
// . .1. mask2 = 4. Here the & failed with . as BOTH ([and]) bits need to be set. Basically it keeps only numbers that have the 3rd bit set
unsigned char mask4 = ( num & 0x10 ) >> 2;
// 0b00101110 num
// 0b00010000 0x10 -> means 16 in decimal or 0b10000 in binary or 2^4 (the power is also the number of trailing 0 after the bit set)
// 0b00.....0 mask4 = 0, all bits failed to be both set
unsigned char mask = mask3 | mask5 ;
// mask will take bits at each position if either set by mask3 [or] mask5 so:
// 0b1001 mask3
// 0boo11 mask4
// 0b1011 mask
return ( num & 0xeb ) | mask; // you now know how it works ;) solve this one. PS: operation between Brackets have priority
}
If you are interested to learn the basics of bitwise operators you can take a look at this introduction.
After you build confidence you can try solving algorithms using only bitwise operators, where you will explore even deeper bitwise operations and see its impact on the runtime ;)
I also recommend reading Bit Twiddling Hacks, Oldies but Goodies!
b = ((b * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32; // reverse your byte!
Simple function to understand swap of bit 3 and 5:
if you want to swap bit index 3 and bit index 5, then you have to do the following:
int n = 0b100010
int mask = 0b100000 // keep bit index 5 (starting from index 0)
int mask2 = 0b1000 // keep bit index 3
n = (n & mask) >> 2 | (n & mask2) << 2 | (n & 0b010111);
// (n & mask) >> 2
// the mask index 5 is decrease by 2 position (>>2) and brings along with it the bit located at index 5 that it had captured in n thanks to the AND operand.
// | (n & mask2) << 2
// mask2 is increased by 2 index and set it to 0 since n didn't have a bit set at index 3 originally.
// | (n & 0b010111); // bits 0 1 2 and 4 are preserved
// since we assign the value to n all other bits would have been wiped out if we hadn't kept their original value thanks to the mask on which we do not perform any shift operations.

Bitwise rotate right of 4-bit value

I'm currently trying to control a stepper motor using simple full steps. This means that I'm currently outputting a sequence of values like this:
1000
0100
0010
0001
I thought an easy way to do this was just take my 4-bit value and after each step, perform a rotate right operation. "Code" obviously isn't following any kind of syntax, it's simply there to illustrate my thoughts:
step = 1000;
//Looping
Motor_Out(step)
//Rotate my step variable right by 1 bit
Rotate_Right(step, 1)
My problem is that there obviously isn't any 4-bit simple data types that I can use for this, and if I use an 8-bit unsigned int I will eventually rotate the 1 off to the MSB, which means the 4-bit value I'm actually interested in, will turn into 0000 for a few steps.
I've read that you can use structs and bit-fields to solve this, but the majority of things I read from this is telling me that it's a very bad idea.
With only 4 possible values you would use a table with 9 elements:
unsigned char table_right[] = { [0x1] = 0x8 , [0x2] = 0x1 , [0x4] = 0x2 , [0x8] = 0x4 };
When you need the next value you simply use the current value as the index:
unsigned char current = 0x4; //value is: 0b0100
unsigned char next = table_right[current]; //returns: 0b0010
assert( next == 0x2 );
Doing this in a loop, will loop through all four possible values.
Conveniently, passing an invalid value, will return a zero, so you can write a get function that also asserts next != 0. You should also assert value < 9 before passing the value to the array.
Just use an int to hold the value. When you do the rotate copy the least significant bit to bit 4 and then shift it right by 1:
int rotate(int value)
{
value |= ((value & 1) << 4); // eg 1001 becomes 11001
value >>= 1; // Now value is 1100
return value;
}
The arithmetic for this is simple enough that it will always be faster than the table approach:
constexpr unsigned rotate_right_4bit ( unsigned value )
{
return ( value >> 1 ) | ( ( value << 3 ) & 15 );
}
This turns into 5 lines of branch-free x86 assembly:
lea eax, [0+rdi*8]
shr edi
and eax, 15
or eax, edi
ret
Or, alternatively, if you actually like to see the indexes {3, 2, 1, 0}, then you can split them up into 2 functions, one that "increments" the index, and the other that actually computes the value:
constexpr unsigned decrement_mod4 ( unsigned index )
{
return ( index - 1 ) & 3;
}
constexpr unsigned project ( unsigned index )
{
return 1u << index;
}
IMO the easiest way is:
const unsigned char steps[ 4 ] = { 0x08, 0x04, 0x02, 0x01 };
int stepsIdx = 0;
...
const unsigned char step = steps[ stepsIdx++ ];
stepsIdx = stepsIdx % ( sizeof( steps ) / sizeof( steps[ 0 ] ) );
you can use 10001000b and mod 10000b
and you can get 01000100b 00100010b 00010001b 10001000b repeat.
for example:
char x = 0x88;
Motor_Out(x & 0xf);
Rotate_Right(step, 1);
if I use an 8-bit unsigned int I will eventually rotate the 1 off to the MSB
So use a shift and reinitialize the bit you want when the value goes to zero. C doesn't have a rotate operation anyway, so you'll have to do at least two shifts. (And I suppose C++ doesn't have rotates either.)
x >>= 1;
if (! x) x = 0x08;
Simple, short to write, and obvious in what it does. Yes, it'll compile into a branch (unless the processor has a conditional move operation), but until you have the profiler output to tell you it's important, you just lost more time thinking about it than those processor cycles will ever amount to.
Use an 8-bit data type (like e.g. uint8_t). Initialize it to zero. Set the bit you want to set in the lower four bits of the byte (e.g. value = 0x08).
For each "rotation" take the LSB (least significant bit) and save it. Shift one step right. Overwrite the fourth bit with the bit you saved.
Something like this:
#include <stdio.h>
#include <stdint.h>
uint8_t rotate_one_right(uint8_t value)
{
unsigned saved_bit = value & 1; // Save the LSB
value >>= 1; // Shift right
value |= saved_bit << 3; // Make the saved bit the nibble MSB
return value;
}
int main(void)
{
uint8_t value = 0x08; // Set the high bit in the low nibble
printf("%02hhx\n", value); // Will print 08
value = rotate_one_right(value);
printf("%02hhx\n", value); // Will print 04
value = rotate_one_right(value);
printf("%02hhx\n", value); // Will print 02
value = rotate_one_right(value);
printf("%02hhx\n", value); // Will print 01
value = rotate_one_right(value);
printf("%02hhx\n", value); // Will print 08 again
return 0;
}
Live demonstration.
I would make an array with the values you need and load the correct value from the array. It will take you 4 bytes, it will be fast, and solve your problems even if you start using a different motor type.
for example:
const char values[4]={1,2,4,8};
int current_value = 0;
....
if(++current_value>=4)current_value=0;
motor = values[current_value];
You only need to output 1, 2, 4, and 8. So you can use a counter to mark which bit to set high.
Motor_Out(8 >> i);
i = (i + 1) & 3;
If you want to drive the motor at half steps, you can use an array to store the numbers you need.
const unsigned char out[] = {0x8, 0xc, 0x4, 0x6, 0x2, 0x3, 0x1, 0x9};
Motor_out(out[i]);
i = (i + 1) & 7;
And you can rotate a 4-bit integer like this.
((i * 0x11) >> 1) & 0xf

How to form a character byte by assigning values to each of the bits?

I have a C function which accepts a character. I need to extract as well insert bits into that character. I am clear with the extraction part. Can anyone give me an idea of how to insert values to bits?
Pretty vague question, I would suggest you brush up on bitwise operators. This should point you in the right direction.
http://www.cprogramming.com/tutorial/bitwise_operators.html
Since you requested for idea and not exact implementation:
Here is what you can do,
Iterate over each bit and set it as required.
You can set the nth bit (0 indexed as follows)
byteVal = byteVal | (1<<N);
Say you want to check the nth bit of a char:
int checkBit(char c, int n) {
return c & (1 << n);
}
To set the nth bit:
void setBit(char *c, int n) {
*c |= 1 << n;
}
If you want to set the Nth bit in a character to 1, you need to OR it with the value 1 shifted to the left by N positions:
c |= 1 << N;
Sure, simply resort to binary operations. The following function should do exactly what you want, but with a simple interface:
char set8 (char ch, int index) {
if (index >= 1 && index <= 8) {
return (char)(ch | (1 << index - 1));
}
return ch;
}
int n = 0;
set8(n, 1); // Returns 1
set8(n, 2); // Returns 2
set8(n, 3); // Returns 4
...
set8(n, 9); // Returns n (0)
The function uses bitwise-OR to toggle the specified bit. If the index specified is outside the range of a byte (8 bits), then it simply returns the character passed in.

How to define and work with an array of bits in C?

I want to create a very large array on which I write '0's and '1's. I'm trying to simulate a physical process called random sequential adsorption, where units of length 2, dimers, are deposited onto an n-dimensional lattice at a random location, without overlapping each other. The process stops when there is no more room left on the lattice for depositing more dimers (lattice is jammed).
Initially I start with a lattice of zeroes, and the dimers are represented by a pair of '1's. As each dimer is deposited, the site on the left of the dimer is blocked, due to the fact that the dimers cannot overlap. So I simulate this process by depositing a triple of '1's on the lattice. I need to repeat the entire simulation a large number of times and then work out the average coverage %.
I've already done this using an array of chars for 1D and 2D lattices. At the moment I'm trying to make the code as efficient as possible, before working on the 3D problem and more complicated generalisations.
This is basically what the code looks like in 1D, simplified:
int main()
{
/* Define lattice */
array = (char*)malloc(N * sizeof(char));
total_c = 0;
/* Carry out RSA multiple times */
for (i = 0; i < 1000; i++)
rand_seq_ads();
/* Calculate average coverage efficiency at jamming */
printf("coverage efficiency = %lf", total_c/1000);
return 0;
}
void rand_seq_ads()
{
/* Initialise array, initial conditions */
memset(a, 0, N * sizeof(char));
available_sites = N;
count = 0;
/* While the lattice still has enough room... */
while(available_sites != 0)
{
/* Generate random site location */
x = rand();
/* Deposit dimer (if site is available) */
if(array[x] == 0)
{
array[x] = 1;
array[x+1] = 1;
count += 1;
available_sites += -2;
}
/* Mark site left of dimer as unavailable (if its empty) */
if(array[x-1] == 0)
{
array[x-1] = 1;
available_sites += -1;
}
}
/* Calculate coverage %, and add to total */
c = count/N
total_c += c;
}
For the actual project I'm doing, it involves not just dimers but trimers, quadrimers, and all sorts of shapes and sizes (for 2D and 3D).
I was hoping that I would be able to work with individual bits instead of bytes, but I've been reading around and as far as I can tell you can only change 1 byte at a time, so either I need to do some complicated indexing or there is a simpler way to do it?
Thanks for your answers
If I am not too late, this page gives awesome explanation with examples.
An array of int can be used to deal with array of bits. Assuming size of int to be 4 bytes, when we talk about an int, we are dealing with 32 bits. Say we have int A[10], means we are working on 10*4*8 = 320 bits and following figure shows it: (each element of array has 4 big blocks, each of which represent a byte and each of the smaller blocks represent a bit)
So, to set the kth bit in array A:
// NOTE: if using "uint8_t A[]" instead of "int A[]" then divide by 8, not 32
void SetBit( int A[], int k )
{
int i = k/32; //gives the corresponding index in the array A
int pos = k%32; //gives the corresponding bit position in A[i]
unsigned int flag = 1; // flag = 0000.....00001
flag = flag << pos; // flag = 0000...010...000 (shifted k positions)
A[i] = A[i] | flag; // Set the bit at the k-th position in A[i]
}
or in the shortened version
void SetBit( int A[], int k )
{
A[k/32] |= 1 << (k%32); // Set the bit at the k-th position in A[i]
}
similarly to clear kth bit:
void ClearBit( int A[], int k )
{
A[k/32] &= ~(1 << (k%32));
}
and to test if the kth bit:
int TestBit( int A[], int k )
{
return ( (A[k/32] & (1 << (k%32) )) != 0 ) ;
}
As said above, these manipulations can be written as macros too:
// Due order of operation wrap 'k' in parentheses in case it
// is passed as an equation, e.g. i + 1, otherwise the first
// part evaluates to "A[i + (1/32)]" not "A[(i + 1)/32]"
#define SetBit(A,k) ( A[(k)/32] |= (1 << ((k)%32)) )
#define ClearBit(A,k) ( A[(k)/32] &= ~(1 << ((k)%32)) )
#define TestBit(A,k) ( A[(k)/32] & (1 << ((k)%32)) )
typedef unsigned long bfield_t[ size_needed/sizeof(long) ];
// long because that's probably what your cpu is best at
// The size_needed should be evenly divisable by sizeof(long) or
// you could (sizeof(long)-1+size_needed)/sizeof(long) to force it to round up
Now, each long in a bfield_t can hold sizeof(long)*8 bits.
You can calculate the index of a needed big by:
bindex = index / (8 * sizeof(long) );
and your bit number by
b = index % (8 * sizeof(long) );
You can then look up the long you need and then mask out the bit you need from it.
result = my_field[bindex] & (1<<b);
or
result = 1 & (my_field[bindex]>>b); // if you prefer them to be in bit0
The first one may be faster on some cpus or may save you shifting back up of you need
to perform operations between the same bit in multiple bit arrays. It also mirrors
the setting and clearing of a bit in the field more closely than the second implemention.
set:
my_field[bindex] |= 1<<b;
clear:
my_field[bindex] &= ~(1<<b);
You should remember that you can use bitwise operations on the longs that hold the fields
and that's the same as the operations on the individual bits.
You'll probably also want to look into the ffs, fls, ffc, and flc functions if available. ffs should always be avaiable in strings.h. It's there just for this purpose -- a string of bits.
Anyway, it is find first set and essentially:
int ffs(int x) {
int c = 0;
while (!(x&1) ) {
c++;
x>>=1;
}
return c; // except that it handles x = 0 differently
}
This is a common operation for processors to have an instruction for and your compiler will probably generate that instruction rather than calling a function like the one I wrote. x86 has an instruction for this, by the way. Oh, and ffsl and ffsll are the same function except take long and long long, respectively.
You can use & (bitwise and) and << (left shift).
For example, (1 << 3) results in "00001000" in binary. So your code could look like:
char eightBits = 0;
//Set the 5th and 6th bits from the right to 1
eightBits &= (1 << 4);
eightBits &= (1 << 5);
//eightBits now looks like "00110000".
Then just scale it up with an array of chars and figure out the appropriate byte to modify first.
For more efficiency, you could define a list of bitfields in advance and put them in an array:
#define BIT8 0x01
#define BIT7 0x02
#define BIT6 0x04
#define BIT5 0x08
#define BIT4 0x10
#define BIT3 0x20
#define BIT2 0x40
#define BIT1 0x80
char bits[8] = {BIT1, BIT2, BIT3, BIT4, BIT5, BIT6, BIT7, BIT8};
Then you avoid the overhead of the bit shifting and you can index your bits, turning the previous code into:
eightBits &= (bits[3] & bits[4]);
Alternatively, if you can use C++, you could just use an std::vector<bool> which is internally defined as a vector of bits, complete with direct indexing.
bitarray.h:
#include <inttypes.h> // defines uint32_t
//typedef unsigned int bitarray_t; // if you know that int is 32 bits
typedef uint32_t bitarray_t;
#define RESERVE_BITS(n) (((n)+0x1f)>>5)
#define DW_INDEX(x) ((x)>>5)
#define BIT_INDEX(x) ((x)&0x1f)
#define getbit(array,index) (((array)[DW_INDEX(index)]>>BIT_INDEX(index))&1)
#define putbit(array, index, bit) \
((bit)&1 ? ((array)[DW_INDEX(index)] |= 1<<BIT_INDEX(index)) \
: ((array)[DW_INDEX(index)] &= ~(1<<BIT_INDEX(index))) \
, 0 \
)
Use:
bitarray_t arr[RESERVE_BITS(130)] = {0, 0x12345678,0xabcdef0,0xffff0000,0};
int i = getbit(arr,5);
putbit(arr,6,1);
int x=2; // the least significant bit is 0
putbit(arr,6,x); // sets bit 6 to 0 because 2&1 is 0
putbit(arr,6,!!x); // sets bit 6 to 1 because !!2 is 1
EDIT the docs:
"dword" = "double word" = 32-bit value (unsigned, but that's not really important)
RESERVE_BITS: number_of_bits --> number_of_dwords
RESERVE_BITS(n) is the number of 32-bit integers enough to store n bits
DW_INDEX: bit_index_in_array --> dword_index_in_array
DW_INDEX(i) is the index of dword where the i-th bit is stored.
Both bit and dword indexes start from 0.
BIT_INDEX: bit_index_in_array --> bit_index_in_dword
If i is the number of some bit in the array, BIT_INDEX(i) is the number
of that bit in the dword where the bit is stored.
And the dword is known via DW_INDEX().
getbit: bit_array, bit_index_in_array --> bit_value
putbit: bit_array, bit_index_in_array, bit_value --> 0
getbit(array,i) fetches the dword containing the bit i and shifts the dword right, so that the bit i becomes the least significant bit. Then, a bitwise and with 1 clears all other bits.
putbit(array, i, v) first of all checks the least significant bit of v; if it is 0, we have to clear the bit, and if it is 1, we have to set it.
To set the bit, we do a bitwise or of the dword that contains the bit and the value of 1 shifted left by bit_index_in_dword: that bit is set, and other bits do not change.
To clear the bit, we do a bitwise and of the dword that contains the bit and the bitwise complement of 1 shifted left by bit_index_in_dword: that value has all bits set to one except the only zero bit in the position that we want to clear.
The macro ends with , 0 because otherwise it would return the value of dword where the bit i is stored, and that value is not meaningful. One could also use ((void)0).
It's a trade-off:
(1) use 1 byte for each 2 bit value - simple, fast, but uses 4x memory
(2) pack bits into bytes - more complex, some performance overhead, uses minimum memory
If you have enough memory available then go for (1), otherwise consider (2).

How can I check my byte flag, verifying that a specific bit is at 1 or 0?

I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.
Here's a function that can be used to test any bit:
bool is_bit_set(unsigned value, unsigned bitindex)
{
return (value & (1 << bitindex)) != 0;
}
Explanation:
The left shift operator << creates a bitmask. To illustrate:
(1 << 0) equals 00000001
(1 << 1) equals 00000010
(1 << 3) equals 00001000
So a shift of 0 tests the rightmost bit. A shift of 31 would be the leftmost bit of a 32-bit value.
The bitwise-and operator (&) gives a result where all the bits that are 1 on both sides are set. Examples:
1111 & 0001 equals 0001
1111 & 0010 equals 0010
0000 & 0001 equals 0000.
So, the expression:
(value & (1 << bitindex))
will return the bitmask if the associated bit (bitindex) contains a 1
in that position, or else it will return 0 (meaning it does not contain a 1 at the assoicated bitindex).
To simplify, the expression tests if the result is greater than zero.
If Result > 0 returns true, meaning the byte has a 1 in the tested
bitindex position.
All else returns false meaning the result was zero, which means there's a 0 in tested bitindex position.
Note the != 0 is not required in the statement since it's a bool, but I like to make it explicit.
As an extension of Patrick Desjardins' answer:
When doing bit-manipulation it really helps to have a very solid knowledge of bitwise operators.
Also the bitwise "AND" operator in C is &, so you want to do this:
unsigned char a = 0xAA; // 10101010 in hex
unsigned char b = (1 << bitpos); // Where bitpos is the position you want to check
if(a & b) {
//bit set
}
else {
//not set
}
Above I used the bitwise "AND" (& in C) to check whether a particular bit was set or not. I also used two different ways of formulating binary numbers. I highly recommend you check out the Wikipedia link above.
You can use an AND operator. The example you have: 10101010 and you want to check the third bit you can do: (10101010 AND 00100000) and if you get 00100000 you know that you have the flag at the third position to 1.
Kristopher Johnson's answer is very good if you like working with individual fields like this. I prefer to make the code easier to read by using bit fields in C.
For example:
struct fieldsample
{
unsigned short field1 : 1;
unsigned short field2 : 1;
unsigned short field3 : 1;
unsigned short field4 : 1;
}
Here you have a simple struct with four fields, each 1 bit in size. Then you can write your code using simple structure access.
void codesample()
{
//Declare the struct on the stack.
fieldsample fields;
//Initialize values.
fields.f1 = 1;
fields.f2 = 0;
fields.f3 = 0;
fields.f4 = 1;
...
//Check the value of a field.
if(fields.f1 == 1) {}
...
}
You get the same small size advantage, plus readable code because you can give your fields meaningful names inside the structure.
If you are using C++ and the standard library is allowed, I'd suggest storing your flags in a bitset:
#include <bitset>
//...
std::bitset<8> flags(someVariable);
as then you can check and set flags using the [] indexing operator.
Nobody's been wrong so far, but to give a method to check an arbitrary bit:
int checkBit( byte in, int bit )
{
return in & ( 1 << bit );
}
If the function returns non-zero, the bit is set.
byte THIRDBIT = 4; // 4 = 00000100 i.e third bit is set
int isThirdBitSet(byte in) {
return in & THIRDBIT; // Returns 1 if the third bit is set, 0 otherwise
}
Traditionally, to check if the lowest bit is set, this will look something like:
int MY_FLAG = 0x0001;
if ((value & MY_FLAG) == MY_FLAG)
doSomething();
You can do as Patrick Desjardins says and you make a bit-to-bit OR to the resulting of the previous AND operation.
In this case, you will have a final result of 1 or 0.
Use a bitwise (not logical!) AND to compare the value against a bitmask.
if (var & 0x08) {
/* The fourth bit is set */
}

Resources