0

I want to a write a program that converts a number to binary and hex.I tried to do this but It gives me the wrong result

int n, c, k;
int t = 0;
int binary[8];
for (c = 31; c >= 0; c--) {
    k = num >> c;
    if (k & 1) {
        printf("1");
        int binary[t] = 1;
    } else {
        printf("0");
        int binary[t] = 0;
    }
    ++t;
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
We Que
  • 5
  • 3
  • Just a sidenote, if you try to convert floating pt numbers in future into there corresponding binary or hexa, you may stumble across [this](https://stackoverflow.com/q/2100490/11498773) – Mihir Luthra Sep 18 '19 at 02:05
  • https://www.geeksforgeeks.org/program-decimal-binary-conversion/ https://stackoverflow.com/questions/5488377/converting-an-integer-to-binary-in-c – EsmaeelE Sep 18 '19 at 02:47
  • 1
    A few observations: (1) if you want to store values in your `binary` array, just use `binary[t] = ...`. The extra `int` on those lines is meaningless and is causing problems. (2) Decide whether you want to print `1`/`0` out immediately, or store it in an array; you probably don't want to do both. (3) If you're making 32 trips through this loop and filling in the array, you had better make your `binary[]` array that big, too. But other than those points, it looks like your code would work. (For binary conversion, at least. Hex will be another story.) – Steve Summit Sep 18 '19 at 02:54
  • 1
    1. Please tell us which output on which input you expect and what you get. – the busybee Sep 18 '19 at 05:48
  • 2. Now that I have edited your code, can you see errors? – the busybee Sep 18 '19 at 05:49

0 Answers0