-1

I am fairly new to programming. I am having trouble converting a decimal int to a binary int. The goal is to input two ASCII values (lets say they are AB) and convert that into a binary integer without using arrays to store the binary value. I have tried many things to try and fix the problem but the logic that I have in my program is very logical and makes sense to me. The output of the program is 1488373225 if you input an 'AB'. Thanks in advance!

Here is my code:

 int converttoBinary(char input[MAX_1]){

    int temp2 = 0, rem = 0, i = 1, binary = 0, temp = 0;

    printf("\n");
    temp = input[0];
    temp2 = input[1] * 100;
    temp = temp + temp2;

    printf("%d", temp);
    while (temp > 0){
            rem = temp % 2;
            binary += rem * i;
            i *= 10;
            temp /= 2;
    }

    printf("The final binary value of %s is: %d", input, binary);

return binary;
}
sarah
  • 59
  • 1
  • 5
  • How are you going to store a base conversion without an array? Representing a number in any particular base only makes sense in the context of textual representation – Govind Parmar Feb 17 '19 at 18:05
  • @GovindParmar You can store it using a single int and for each place you can multiply the number by a value of 10 – sarah Feb 17 '19 at 18:13
  • So, you want to print decimal number as a binary? What is expected result? If you want to print decimal in binary format look at this https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format – alberand Feb 17 '19 at 18:48
  • Your program _does_ output `1488373225` for an input of `AB`. So, what _should_ it be outputting? What is `AB`? Is it hex [as it sure isn't decimal]? I think you need to add more explanation as to what you mean: what is the input format _exactly_, what output do you want, a few more input/output pairs would help. You are multiplying by 100 and _not_ 10 as you mention in your comment. – Craig Estey Feb 17 '19 at 18:58
  • @CraigEstey it should be outputting 0110010101100110 – sarah Feb 17 '19 at 19:12
  • @A.Albershteyn I looked at that and I get errors if I try to print it as %b, that is why I am going this route. – sarah Feb 17 '19 at 19:16
  • @sarah In the link which I attached is `%c` – alberand Feb 17 '19 at 19:28

1 Answers1

0

The reason your code is not working is because the int in C is not big enough to store this 15 digit number, so you got an overflow. try running your code on one char only and you'll see it works just fine.
As already said in the comment - it doesn't make sense to store this "binary" in an int, you should probably store it as a string. And if you only need to print the binary format, you can just print the digit in the loop instead of storing the whole binary.
Another small thing - it doesn't affect the result of the code, but when doing bitwise operations it's better practice to use the bitwise operators - in your case & 1 insted of % 2 and >> 1 instead of / 2.