How to set the 513rd bit of char [1024] in C?

I recently asked in an interview how to set the 513rd bit of char[1024] in C, but I'm not sure how to approach the problem. I saw. How do you set, clear and switch one bit? but how to select a bit from such a large array?

+4
source share
6 answers
 int bitToSet = 513; inArray[bitToSet / 8] |= (1 << (bitToSet % 8)); 

... making certain assumptions about the size of the character and the degree desired.

EDIT: Good, great. You can replace 8 with CHAR_BIT if you want.

+8
source
 #include <limits.h> int charContaining513thBit = 513 / CHAR_BIT; int offsetOf513thBitInChar = 513 - charContaining513thBit*CHAR_BIT; int bit513 = array[charContaining513thBit] >> offsetOf513thBitInChar & 1; 
+4
source

You need to know the character width (in bits) on your computer. For almost everyone, this is 8. You can use the CHAR_BIT constant from limits.h in a C program. Then you can do some pretty simple math to find the bit offset (depending on how you count them).

The numbering of bits is on the left, with bit 2 "per bit [0] - bit 0, bit 2 bit - bit 7, and bit 2 bits in [1] - bit 8, this gives:

 offset = 513 / CHAR_BIT; /* using integer (truncating) math, of course */ bit = 513 % CHAR_BIT; a[offset] |= (0x80>>bit) 

There are many reasonable ways to number bits, here are two:

  a[0] a[1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 This is the above 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 This is |= (1<<bit) 

You can also specify a number from the other end of the array (treating it as a very large large number).

+2
source

Minor optimization:

The operators / and% are rather slow, even on many modern processors, and the module is slightly slower. I would replace them with equivalent operations using bit offsets (and subtraction), which only works well when the second operand is a power of two, obviously.

x / 8 becomes x → 3
x% 8 becomes x - ((x → 3) <3)
for this second operation, simply reuse the result from the initial division.

+2
source

Depending on the desired order (from left to right and from right to left), it can change. But a general idea, assuming 8 bits per byte, would be to select a byte like. This is expanded into many lines of code to hopefully show the intended steps more clearly (or perhaps it just confuses the intention):

 int bitNum = 513; int bytePos = bitNum / 8; 

Then the position of the bit will be calculated as:

 int bitInByte = bitNum % 8; 

Then set the bit (it is assumed that the goal is to set it to 1, not transparency or toggle it):

 charArray[bytePos] |= ( 1 << bitInByte ); 
+1
source

When you say that 513 you use the index 0 or 1 for the 1st bit? If this is the first, your message refers to a bit with index 512. I think the question is correct, since everywhere in C the first index is always 0.

By the way

 static char chr[1024]; ... chr[512>>3]=1<<(512&0x7); 
0
source

All Articles