-1

this is my code , I think something wrong with the shift operator , I used them in embedded software but I don't know if it is ok to use them on normal code , I have written a code to do the same purpose but with the method of adding (2*10^digit) but it seems a lot easier to use shifts-if possible-, please help :

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

double find_power(double x);
int main()
{
    double bin=00000000, dec , k ;
    printf("enter decimal number:\n");
    scanf("%d",&dec);
    for(;;)
    {
        k=find_power(dec);
        bin|=(1<<k);
        dec-=pow(2,k);
        if(dec==1)
        {
            bin|=(1<<0);
            break;
        }
        else if(dec==0)
        {
            bin&=(~(1<<0));
            break;
        }

    }

    printf("%d",bin);
    return 0;
}

double find_power(double x)
{
    double i=1,j=0;
    for(;;)
    {
        i*=2;
        if(x>=i)
        {
            j++;
        }
        else if(x<i)
        {
             break;
        }

    }
    return j;
}
LPs
  • 16,045
  • 8
  • 30
  • 61

1 Answers1

-1

You are wildly mixing double and int all over the code. You try to read an int into a double with scanf, which invokes undefined behavior. And then you try to use double variables together with bitwise operators, which most likely doesn't make any sense. You'll want to use an unsigned integer of known size instead.

You should enable/listen to compiler warnings.

Lundin
  • 195,001
  • 40
  • 254
  • 396