Skip to content

Instantly share code, notes, and snippets.

@Hritik14
Created July 23, 2020 14:27
Show Gist options
  • Save Hritik14/bfd9880cbaa85ec107426b54978a1021 to your computer and use it in GitHub Desktop.
Save Hritik14/bfd9880cbaa85ec107426b54978a1021 to your computer and use it in GitHub Desktop.
Convert decimal to binary using bitwise operations. [Supports showing the memory of floats as well]
#include<stdio.h>
#include<string.h>
/*
* bitwisei -- decimal to binary using bitwise operators
* masks n with 0001
* then with 0010
* then with 0100
* then with 100
* in order to find out if the corresponding bit is on in n
* n: number int decimal
* buf: buffer for output, must be able to contain
* sizeof(n)*8 char + '\0'
*/
int bitwisei(int n, char* buf){
int i, ri;
ri=sizeof(n)*8;
buf[ri--] = '\0';
for(i=0; i < sizeof(n) * 8; i++)
buf[ri--] = (n & 1<<i)?'1':'0';
return 0;
}
/*
* same as above, just for floats
*/
int bitwisef(float f, char* buf){
int n;
if (sizeof(f) != sizeof(int)){
buf[0]='\0';
return -1;
}
memcpy(&n, &f, sizeof(f));
return bitwisei(n, buf);
}
int main(){
float f;
char opt;
char buf[100];
scanf("%f%c", &f, &opt);
if (opt == 'i' || opt == '\n')
bitwisei(f, buf);
else if(opt == 'f')
bitwisef(f, buf);
puts(buf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment