Convert decimal to binary in C

后端 未结 16 770
攒了一身酷
攒了一身酷 2020-12-10 09:38

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         


        
16条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 10:15

    So... did you check the output of your code to understand why it doesn't work?

    So iteration 1 of your loop:
    value = 192
    i = 4
    output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
    
    Iteration 2 of your loop:
    value = 96
    i = 3
    output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
    
    Iteration 3 of your loop:
    value = 48
    i = 2
    output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
    
    Iteration 4 of your loop:
    value = 24
    i = 1
    output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
    
    Iteration 5 of your loop:
    value = 12
    i = 0
    output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
    
    Final string: "00000"  and you wanted: "11000000"
    

    See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:

    output[8] = '\0';
    for (i = 7; i >= 0; --i, value >>= 1)
    

    And then you'll have the correct result returned.

    I would recomend just a more general approach, you're using a fixed length string, which limits you to binary numbers of a certian length. You might want to do something like:

    loop while number dividing down is > 0
    count number of times we loop
    malloc an array the correct length and be returned
    

提交回复
热议问题