PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] Why do bits repeat when I convert a base-10 number into a base-2 number?

 August 07, 2022     binary, c, decimal     No comments   

Issue

I have a simple question. I wrote this small function that is supposed to get a unsigned base-10 number, and then print it in its binary representation with 64-bits. I noticed a peculiar detail in what my code produces even though it seems like I have done nothing wrong. It seems that the bits repeat themselves! I try print a base-10 "1", and the number is right but when it reaches the 32'nd bit that is when I notice the number repeats! Example: If I want to my program to print a 1 in a 64-bit binary representation then I should get 0000000000000000000000000000000000000000000000000000000000000001. Instead, I get 0000000000000000000000000000000100000000000000000000000000000001. This is the same for every number I have tried, and I do not know why this is happening. Oh, dear programmers of Stack Overflow what is going on! I could use your brain and knowledge thank you very much. Any help is appreciated even if you point me to an online article.

    #include <stdio.h>

    void decToBinary(int base_10_number);

    int main(void)
    {
        decToBinary(1);
        return 0;
    }

    /* decToBinary: converts a base 10 number into a base 2 number and prints the result */
    void decToBinary(int base_10_number)
    {
         unsigned short bitmap[64];

        for (int index = 0, pos = 63; index < 64; index++, pos--)
            bitmap[pos] = 1 << index & base_10_number;
    
        for (int control = 0; control < 64; control++)
            printf("%i", bitmap[control]);
    
        putchar('\n');
    }

Solution

1 << something is only good for something in the 0 to 30 or 31. That is 32-bit int math.

//                               vv----- too big
for (int index = 0, ...; index < 64; index++, ...)
    bitmap[pos] = 1 << index & base_10_number;

Beyond that, it is undefined behavior.

Perhaps the shift ony looked at the 5 least significant bits of something.


Try

for (int index = 0; index < 32; index++)
        bitmap[32 - 1 - index] = ((1u << index) & base_10_number) != 0;

for (int control = 0; control < 32; control++)
        printf("%i", bitmap[control]);


Answered By - chux - Reinstate Monica
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing