I am reviewing for an exam and have a practice problem that I'm stuck on.
I need to write the function find_sequence(unsigned int num, unsigned int patter) {}.
I have tried comparing num & (pattern << i) == (pattern << i) and other things like that but it keeps saying there is a pattern when there isn't. I see why it is doing that but I can not fix it.
The num I'm using is unsigned int a = 82937 and I'm searching for pattern unsigned int b = 0x05.
Pattern: 00000000000000000000000000000101
Original bitmap: 00000000000000010100001111111001
The code so far:
int find_sequence(unsigned int num, unsigned int pattern)
{
for (int i=0; i<32; i++)
{
if ((num & (pattern << i)) == (pattern << i))
{
return i;
}
}
return -9999;
}
int
main()
{
unsigned int a = 82937;
unsigned int b = 0x05;
printf("Pattern: ");
printBits(b);
printf("\n");
printf("Original bitmap: ");
printBits(a);
printf("\n");
int test = find_sequence(a, b);
printf("%d\n", test);
return 0;
}
Here is what I have so far. This keeps returning 3, and I see why but I do not know how to avoid it.
for (int i=0; i<32; i++)
{
if ((num & (pattern << i)) == (pattern << i))
is bad:
- it works only when pattern consists of 1 entirely
- you generate at the end of the loop pattern << 31 which is 0 when pattern is even. Condition will hold every time then.
Knowing the length of the pattern would simplify the loop above; just go until 32 - size. When not given by the API, the length can be calculated either by a clz() function or manually by looping over the bits.
Now, you can generate the mask as mask = (1u << length) - 1u (note: you have to handle the length == 32 case in a special way) and write
for (int i=0; i < (32 - length); i++)
{
if ((num & (mask << i)) == (pattern << i))
or
for (int i=0; i < (32 - length); i++)
{
if (((num >> i) & mask) == pattern)
((num & (pattern << i)) == (pattern << i)) won't give you the desire results.
Let's say you pattern is 0b101 and the value is 0b1111, then
0101 pattern
1111 value
& ----
0101 pattern
Even though the value has not the pattern 0b101, the check would return true.
You've got to create a mask where all bits of the pattern (until the most
significant bit) are 1 and the rest are 0. So for the pattern 0b101 the mask
must be b111.
So first you need to calculate the position of the most significant bit of the pattern, then create
the mask and then you can apply (bitwise AND) the mask to the value. If the
result is the same as the pattern, then you've found your pattern:
int find_sequence(unsigned int num, unsigned int pattern)
{
unsigned int copy = pattern;
// checking edge cases
if(num == 0 && pattern == 0)
return 0;
if(num == 0)
return -1;
// calculating msb of pattern
int msb = -1;
while(copy)
{
msb++;
copy >>= 1;
}
printf("msb of pattern at pos: %d\n", msb);
// creating mask
unsigned int mask = (1U << msb + 1) - 1;
int pos = 0;
while(num)
{
if((num & mask) == pattern)
return pos;
num >>= 1;
pos++;
}
return -1;
}
Using this function I get the value 14, where your 0b101 pattern is found in
a.
In this case you could make a bitmask that 0's out all the spaces you aren't looking for so in this case
Pattern: 00000000000000000000000000000101
Bitmask: 00000000000000000000000000000111
So in the case of the number you are looking at
Original: 00000000000000010100001111111001
If you and that with this bitmask you end of with
Number after &: 00000000000000000000000000000001
And compare the new number with your pattern to see if equal.
Then >> the original number
Original: 00000000000000010100001111111001
Right shifted: 00000000000000001010000111111100
And repeat the & and compare to check the next 3 numbers in the sequence.
Related
Dear all C programmer:
X = 1 << N; (left shift)
how to recover N from X ?
Thanks
N in this case is the bit position where you shifted in a 1 at. Assuming that X here only got one bit set. Then to find out what number that bit position corresponds to, you have to iterate through the data and mask with bitwise AND:
for(size_t i=0; i<sizeof(X)*8; i++)
if(X & (1<<i))
printf("%d", i);
If performance is important, then you'd make a look-up table with all possible results instead.
In a while loop, keep shifting right until X==1, record how many times you have to shift right and the counter will give you N.
int var = X;
int count = 0;
while (var != 1){
var >>= 1;
count++;
}
printf("N is %d", count);
Try this (flsl from here which is available from string.h on macOS) :
int flsl(long mask)
{
int bit;
if (mask == 0) return (0);
for (bit = 1; mask != 1; bit++)
mask = (unsigned long)mask >> 1;
return (bit);
}
unsigned char binlog(long mask) { return mask ? flsl(mask) - 1 : 0; }
int x = 1 << 20;
printf("%d\n", binlog(x)); ===> 20
I have a function that read a word, bit by bit and change to symbol:
I need help to change it to read every 2 bits and change to symbol.
I don't have an idea for it and I need your help guys
void PrintWeirdBits(word w , char* buf){
word mask = 1<<(BITS_IN_WORD-1);
int i;
for(i=0;i<BITS_IN_WORD;i++){
if(mask & w)
buf[i]='/';
else
buf[i]='.';
mask>>=1;
}
buf[i] = '\0';
}
Needed symbols:
00 - *
01 - #
10 - %
11 - !
Here is my proposal for your issue.
Using a lookup table for the symbol decoding will eliminate the need in if statements.
(I assumed word is an unsigned 16 bits data type)
#define BITS_PER_SIGN 2
#define BITS_PER_SIGN_MSK 3 // decimal 3 is 0b11 in binary --> two bits set
// General define could be:
// ((1u << BITS_PER_SIGN) - 1)
#define INIT_MASK (BITS_PER_SIGN_MSK << (BITS_IN_WORD - BITS_PER_SIGN))
void PrintWeirdBits(word w , char* buf)
{
static const char signs[] = {'*', '#', '%', '!'};
unsigned mask = INIT_MASK;
int i;
int sign_idx;
for(i=0; i < BITS_IN_WORD / BITS_PER_SIGN; i++)
{
// the bits of the sign represent the index in the signs array
// just need to align these bits to start from bit 0
sign_idx = (w & mask) >> (BITS_IN_WORD - (i + 1)*BITS_PER_SIGN);
// store the decoded sign in the buffer
buf[i] = signs[sign_idx];
// update the mask for the next symbol
mask >>= BITS_PER_SIGN;
}
buf[i] = '\0';
}
Here it seems to be working.
With small effort it can be updated to a generic code for any bit width of the symbol as long as it is power of two (1, 2, 4, 8) and smaller that BITS_IN_WORD.
Assuming word is unsigned int or an unsigned integer type.
void PrintWeirdBits(word w , char* buf){
word mask = 3 << (BITS_IN_WORD -2);
int i;
word cmp;
for(i=0;i<BITS_IN_WORD/2;i++){
cmp = (mask & w) >> (BITS_IN_WORD -2 -2i);
if(cmp == 0x00)
{
buf[i]='*';
}
else if (cmp == 0x01)
{
buf[i]='#';
}
else if (cmp == 0x02)
{
buf[i]='%';
}
else
{
buf[i]='!';
}
mask>>=2;
}
buf[i] = '\0';
}
The important part is
cmp = (mask & w) >> (BITS_IN_WORD -2 -2i);
Here mask and the input w is bitwise ANDed and the result is right shifted to get the value in the first two bits. These bits are compared to get the result.
I'm wondering if someone know effective approach to calculate bits in specified position along array?
Assuming that OP wants to count active bits
size_t countbits(uint8_t *array, int pos, size_t size)
{
uint8_t mask = 1 << pos;
uint32_t result = 0;
while(size--)
{
result += *array++ & mask;
}
return result >> pos;
}
You can just loop the array values and test for the bits with a bitwise and operator, like so:
int arr[] = {1,2,3,4,5};
// 1 - 001
// 2 - 010
// 3 - 011
// 4 - 100
// 5 - 101
int i, bitcount = 0;
for (i = 0; i < 5; ++i){
if (arr[i] & (1 << 2)){ //testing and counting the 3rd bit
bitcount++;
}
}
printf("%d", bitcount); //2
Note that i opted for 1 << 2 which tests for the 3rd bit from the right or the third least significant bit just to be easier to show. Now bitCount would now hold 2 which are the number of 3rd bits set to 1.
Take a look at the result in Ideone
In your case you would need to check for the 5th bit which can be represented as:
1 << 4
0x10000
16
And the 8th bit:
1 << 7
0x10000000
256
So adjusting this to your bits would give you:
int i, bitcount8 = 0, bitcount5 = 0;
for (i = 0; i < your_array_size_here; ++i){
if (arr[i] & 0x10000000){
bitcount8++;
}
if (arr[i] & 0x10000){
bitcount5++;
}
}
If you need to count many of them, then this solution isn't great and you'd be better off creating an array of bit counts, and calculating them with another for loop:
int i, j, bitcounts[8] = {0};
for (i = 0; i < your_array_size_here; ++i){
for (j = 0; j < 8; ++j){
//j will be catching each bit with the increasing shift lefts
if (arr[i] & (1 << j)){
bitcounts[j]++;
}
}
}
And in this case you would access the bit counts by their index:
printf("%d", bitcounts[2]); //2
Check this solution in Ideone as well
Let the bit position difference (e.g. 7 - 4 in this case) be diff.
If 2diff > n, then code can add both bits at the same time.
void count(const uint8_t *Array, size_t n, int *bit7sum, int *bit4sum) {
unsigned sum = 0;
unsigned mask = 0x90;
while (n > 0) {
n--;
sum += Array[n] & mask;
}
*bit7sum = sum >> 7;
*bit4sum = (sum >> 4) & 0x07;
}
If the processor has a fast multiply and n is still not too large, like n < pow(2,14) in this case. (Or n < pow(2,8) in the general case)
void count2(const uint8_t *Array, size_t n, int *bit7sum, int *bit4sum) {
// assume 32 bit or wider unsigned
unsigned sum = 0;
unsigned mask1 = 0x90;
unsigned m = 1 + (1u << 11); // to move bit 7 to the bit 18 place
unsigned mask2 = (1u << 18) | (1u << 4);
while (n > 0) {
n--;
sum += ((Array[n] & mask1)*m) & mask2;
}
*bit7sum = sum >> 18;
*bit4sum = ((1u << 18) - 1) & sum) >> 4);
}
Algorithm: code is using a mask, multiply, mask to separate the 2 bits. The lower bit remains in it low position while the upper bit is shifted to the upper bits. Then a parallel add occurs.
The loop avoids any branching aside from the loop itself. This can make for fast code. YMMV.
With even larger n, break it down into multiple calls to count2()
I want to create a rand() range between 1 and the dynamic value of bit_cnt.
After reading more about the rand() function, I understand that out of the box rand() has a range of [0, RAND_MAX]. I also understand that RAND_MAX's value is library-dependent, but is guaranteed to be at least 32767.
I had to create a bit mask of 64 0s.
Now, I am trying to left shift the bit mask by a dynamic value of bit_cnt anded with the a randomly generated number of bits between 1 and the dynamic value of bit_cnt.
For example, when bit_cnt is 10, I want to randomize the lowest 10 bits.
Originally, I had
mask = (mask << bit_cnt) + (rand()% bit_cnt);
which caused a floating point exception. From what I am understanding, that exception occurred because the value of bit_cntbecame 0.
Therefore, I attempted to create an if statement like this:
if((rand()%bit_cnt))!=0){
mask = (mask << bit_cnt) + (rand()% bit_cnt);
}
,but the floating point exception still occurred.
Then I tried the following thinking that the value not be 0 so increase the value to at least 1:
mask = (mask << bit_cnt) + ((rand()% bit_cnt)+1);
,but the floating point exception still occurred.
Afterwards, I tried the following:
mask = (mask << bit_cnt) + (1+(rand()%(bit_cnt+1)));
and the following 20 lines of 64 bits outputted:
0000000000000000000000000000000000000000000000000000000000000010
0000000000000000000000000000000000000000000000000000000000000011
0000000000000000000000000000000000000000000000000000000000000101
0000000000000000000000000000000000000000000000000000000000001010
0000000000000000000000000000000000000000000000000000000000010011
0000000000000000000000000000000000000000000000000000000000100011
0000000000000000000000000000000000000000000000000000000001000110
0000000000000000000000000000000000000000000000000000000010000100
0000000000000000000000000000000000000000000000000000000100001001
0000000000000000000000000000000000000000000000000000001000000010
0000000000000000000000000000000000000000000000000000010000000100
0000000000000000000000000000000000000000000000000000100000000111
0000000000000000000000000000000000000000000000000001000000000101
0000000000000000000000000000000000000000000000000010000000001001
0000000000000000000000000000000000000000000000000100000000000111
0000000000000000000000000000000000000000000000001000000000001111
0000000000000000000000000000000000000000000000010000000000001010
0000000000000000000000000000000000000000000000100000000000000101
0000000000000000000000000000000000000000000001000000000000001101
0000000000000000000000000000000000000000000010000000000000001100
What was the cause of the floating point exception? Is this how to dynamic create a range of the rand() function?
I appreciate any suggestions. Thank you.
UPDATE:
I changed the if statement to be the following:
if(bit_cnt !=0)
and then performed the rest of the logic.
I received the following output:
0000000000000000000000000000000000000000000000000000000000000001
0000000000000000000000000000000000000000000000000000000000000010
0000000000000000000000000000000000000000000000000000000000000100
0000000000000000000000000000000000000000000000000000000000001000
0000000000000000000000000000000000000000000000000000000000010010
0000000000000000000000000000000000000000000000000000000000100001
0000000000000000000000000000000000000000000000000000000001000100
0000000000000000000000000000000000000000000000000000000010000110
0000000000000000000000000000000000000000000000000000000100000011
0000000000000000000000000000000000000000000000000000001000000000
0000000000000000000000000000000000000000000000000000010000001000
0000000000000000000000000000000000000000000000000000100000000111
0000000000000000000000000000000000000000000000000001000000000110
0000000000000000000000000000000000000000000000000010000000000110
0000000000000000000000000000000000000000000000000100000000001100
0000000000000000000000000000000000000000000000001000000000000010
0000000000000000000000000000000000000000000000010000000000001101
0000000000000000000000000000000000000000000000100000000000000110
0000000000000000000000000000000000000000000001000000000000010000
0000000000000000000000000000000000000000000010000000000000000100
Is there any possible way to know if the range is correct? Like is there any possible way to know by looking at the output?
const int LINE_CNT = 20;
void print_bin(uint64_t num, unsigned int bit_cnt);
uint64_t rand_bits(unsigned int bit_cnt);
int main(int argc, char *argv[]) {
int i;
srand(time(NULL));
for(i = 0; i < LINE_CNT; i++) {
uint64_t val64 = rand_bits(i);
print_bin(val64, 64);
}
return EXIT_SUCCESS;
}
void print_bin(uint64_t num, unsigned int bit_cnt) {
int top_bit_cnt;
if(bit_cnt <= 0) return;
if(bit_cnt > 64) bit_cnt = 64;
top_bit_cnt = 64;
while(top_bit_cnt > bit_cnt) {
top_bit_cnt--;
printf(" ");
}
while(bit_cnt > 0) {
bit_cnt--;
printf("%d", (num & ((uint64_t)1 << bit_cnt)) != 0);
}
printf("\n");
return;
}
uint64_t rand_bits(unsigned int bit_cnt) {
uintmax_t mask = 1;
if (bit_cnt != 0) {
mask = (mask << bit_cnt) + (rand()% bit_cnt);
}
return mask;
}
I am trying to modify the function rand_bits to return all 0 expect for the lowest bits aka bit_cnt which are randomized.
Returns a 64 bit pattern with all zeros except for the lowest requested bits, which are randomized. This allows for arbitrary length random bit patterns in a portable fashion as the C standard "rand()" function is only required to return
random numbers between 0 and 32767... effectively, a random 15 bit pattern.
Parameter, "bit_cnt": How many of the lowest bits, including the lowest order bit (bit 0) to be randomized.
UPDATE: Added Barmar's newest suggestion of mask = rand() % (1 << bit_cnt);:
0000000000000000000000000000000000000000000000000000000000000001
0000000000000000000000000000000000000000000000000000000000000001
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000010
0000000000000000000000000000000000000000000000000000000000001000
0000000000000000000000000000000000000000000000000000000000001001
0000000000000000000000000000000000000000000000000000000000000010
0000000000000000000000000000000000000000000000000000000000010101
0000000000000000000000000000000000000000000000000000000001001111
0000000000000000000000000000000000000000000000000000000010000011
0000000000000000000000000000000000000000000000000000001010101001
0000000000000000000000000000000000000000000000000000010101101100
0000000000000000000000000000000000000000000000000000101011111000
0000000000000000000000000000000000000000000000000001001010101111
0000000000000000000000000000000000000000000000000011101011000101
0000000000000000000000000000000000000000000000000001001101111101
0000000000000000000000000000000000000000000000001111000000111010
0000000000000000000000000000000000000000000000000101100000001100
0000000000000000000000000000000000000000000000100111101000111111
0000000000000000000000000000000000000000000001010101011101000110
uint64_t rand_bits(unsigned int bit_cnt) {
uintmax_t mask = 1;
if (bit_cnt != 0) {
mask = rand() % (1 << bit_cnt);
}
return mask;
}
The problem is that anything % bit_cnt will get an error if bit_cnt is 0. You need to check bit_cnt before you try to perform the modulus.
if (bit_cnt != 0) {
mask = (mask << bit_cnt) + (rand()% bit_cnt) + 1;
}
All your attempts performed the modulus and then tried to do something with the result, but that's after the error happens.
This uses the bit count to generate a mask. If you want a bit count greater than can be filled by RAND_MAX, implement another random function as I commented earlier.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int bit_cnt = 10;
unsigned mask = 0;
int i;
int num;
srand((unsigned)time(NULL));
for(i = 0; i < bit_cnt; i++)
mask = (mask << 1) | 1;
printf ("For bit_cnt=%d, mask=0x%X\n\n", bit_cnt, mask);
for (i = 0; i < 5; i++) {
num = rand() & mask;
printf("Random number 0x%0*X\n", 1+(bit_cnt-1)/4, num);
}
}
Program output:
For bit_cnt=10, mask=0x3FF
Random number 0x327
Random number 0x39C
Random number 0x1B1
Random number 0x088
Random number 0x26E
I'm trying to simply convert a byte received from fget into binary.
I know the value of the first byte was 49 based on printing the value. I now need to convert this into its binary value.
unsigned char byte = 49;// Read from file
unsigned char mask = 1; // Bit mask
unsigned char bits[8];
// Extract the bits
for (int i = 0; i < 8; i++) {
// Mask each bit in the byte and store it
bits[i] = byte & (mask << i);
}
// For debug purposes, lets print the received data
for (int i = 0; i < 8; i++) {
printf("Bit: %d\n",bits[i]);
}
This will print:
Bit: 1
Bit: 0
Bit: 0
Bit: 0
Bit: 16
Bit: 32
Bit: 0
Bit: 0
Press any key to continue . . .
Clearly, this is not a binary value. Any help?
The problem you're having is that your assignment isn't resulting in a true or false value.
bits[i] = byte & (mask << i);
This gets the value of the bit. You need to see if the bit is on or off, like this:
bits[i] = (byte & (mask << i)) != 0;
Change
bits[i] = byte & (mask << i);
to
bits[i] = (byte >> i) & mask;
or
bits[i] = (byte >> i) & 1;
or
bits[i] = byte & 1;
byte >>= 1;
One way, among many:
#include <stdio.h>
#include <limits.h>
int main(void) {
int i;
char bits[CHAR_BIT + 1];
unsigned char value = 47;
for (i = CHAR_BIT - 1; i >= 0; i -= 1) {
bits[i] = '0' + (value & 0x01);
value >>= 1;
}
bits[CHAR_BIT] = 0;
puts(bits);
return 0;
}
You may notice that your output has a couple 1's and 0's, but also powers of 2, such as 32. This is because after you isolate the bit you want using the mask, you still have to bit-shift it into the least-significant digit so that it shows up as a 1. Or you could use what other posts suggested, and instead of bit-shifting the result (something like 00001000 for example), you could simply use (result != 0) to fetch either a 1 or 0, since in C, false is 0, and comparisons such as != will return 1 as true (I think).
#include<Stdio.h>
#include <limits.h>
void main(void) {
unsigned char byte = 49;// Read from file
unsigned char mask = 1; // Bit mask
unsigned char bits[8];
int i, j = CHAR_BIT-1;
// Extract the bits
for ( i = 0; i < 8; i++,j--,mask = 1) {
// Mask each bit in the byte and store it
bits[i] =( byte & (mask<<=j)) != NULL;
}
// For debug purposes, lets print the received data
for (int i = 0; i < 8; i++) {
printf("%d", bits[i]);
}
puts("");
}
This addition in place of that will work:
bits[i]= byte & (mask << i);
bits[i] >>=i;