Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was recently asked in an interview how to set the 513th bit of a char[1024] in C, but I'm unsure how to approach the problem. I saw How do you set, clear, and toggle a single bit?, but how do I choose the bit from such a large array?

like image 781
Gautam Avatar asked Dec 04 '22 06:12

Gautam


2 Answers

int bitToSet = 513;
inArray[bitToSet / 8] |= (1 << (bitToSet % 8));

...making certain assumptions about character size and desired endianness.

EDIT: Okay, fine. You can replace 8 with CHAR_BIT if you want.

like image 88
Chriszuma Avatar answered Dec 19 '22 18:12

Chriszuma


#include <limits.h>

int charContaining513thBit = 513 / CHAR_BIT;
int offsetOf513thBitInChar = 513 - charContaining513thBit*CHAR_BIT;

int bit513 = array[charContaining513thBit] >> offsetOf513thBitInChar & 1;
like image 43
Stephen Canon Avatar answered Dec 19 '22 19:12

Stephen Canon