I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn\'t work:
void de
The value is not decimal. All values in computer's memory are binary.
What you are trying to do is to convert int to a string using specific base.
There's a function for that, it's called itoa
.
http://www.cplusplus.com/reference/cstdlib/itoa/
It looks like this, but be careful, you have to reverse the resulting string :-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char output[256]="";
int main()
{
int x= 192;
int n;
n = x;
int r;
do {
r = n % 2;
if (r == 1)
strcat(output,"1");
else strcat(output,"0");
n = n / 2;
}
while (n > 0);
printf("%s\n",output);
}
number=215
a=str(int(number//128>=1))+str(int(number%128>=64))+
str(int(((number%128)%64)>=32))+str(int((((number%12
8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
+str(int(((((((number%128)%64)%32)%16)%8)>=4)))
+str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
+str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
print(a)
You can also use the 'if', 'else', statements to write this code.
#include <stdio.h>
#include <stdlib.h>
void bin(int num) {
int n = num;
char *s = malloc(sizeof(int) * 8);
int i, c = 0;
printf("%d\n", num);
for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
n = num >> i;
*(s + c) = (n & 1) ? '1' : '0';
c++;
}
*(s + c) = NULL;
printf("%s", s); // or you can also return the string s and then free it whenever needed
}
int main(int argc, char *argv[]) {
bin(atoi(argv[1]));
return EXIT_SUCCESS;
}