Home > other >  Return the bit of a binary value in C
Return the bit of a binary value in C

Time:11-23

I want to implement a function get_bit(value,pos) so that it returns the value of the bit (0 or 1) from the unsigned integer value at index pos. value is an integer.

for example, if value = 5 (0101 in binary) then get_bit(5,0) = 1 and then if get_bit(5,1) = 0 and then get_bit(5,2)=1 and so on.

So far what I tried to do is:

#include <stdio.h>
#include <math.h>

long decimalToBinary(int decimalnum)
{
    long binarynum = 0;
    int rem, temp = 1;

    while (decimalnum!=0)
    {
        rem = decimalnum%2;
        decimalnum = decimalnum / 2;
        binarynum = binarynum   rem*temp;
        temp = temp * 10;
    }
    return binarynum;
}

const char * get_bit(int value, int pos) {
    char  result[99];
    long bin_val = decimalToBinary(value);
    sprintf(result, "%f", bin_val);
    return result[pos];
    
}

int main() {
    printf( get_bit(5,0) );
    return 0;
}

but it is showing segmentation error. Can anybody help to make it work?

CodePudding user response:

As I mentioned on a comment, your return value for get_bit is incorrect. You return result[pos] which is a char value as a char *. printf is then dereferencing an invalid address, thus segfaulting. The following fix is working for me :

#include <stdio.h>
#include <math.h>

long decimalToBinary(int decimalnum)
{
    long binarynum = 0;
    int rem, temp = 1;

    while (decimalnum!=0)
    {
        rem = decimalnum%2;
        decimalnum = decimalnum / 2;
        binarynum = binarynum   rem*temp;
        temp = temp * 10;
    }
    return binarynum;
}

const char get_bit(int value, int pos) {
    char  result[99];
    long bin_val = decimalToBinary(value);
    sprintf(result, "%ld", bin_val);
    return result[pos];
}

int main() {
    int val = 5;
    printf("val(%d) is : 0b%c%c%c\n", val, get_bit(val,0), get_bit(val,1), get_bit(val,2));
    return 0;
}

Outputs :

 val(5) is : 0b101

CodePudding user response:

You can grab the bit as follow then print it.

char get_bit(int value, int pos) {
    long bin_val = decimalToBinary(value);
    cout << "binary value = " << bin_val << endl;
    
    for(int i=0; i<pos; i  )
        bin_val /= 10;
    return bin_val;
}
  •  Tags:  
  • c
  • Related