How to output an integer in binary in the C language?

To output an integer in binary form in the C language, you can achieve this by using bitwise operators and loops. Here is an example code:

#include <stdio.h>

void printBinary(int num) {
    int mask = 1 << 31; // 用于检查每一位的掩码

    printf("Binary representation of %d is: ", num);

    for(int i = 0; i < 32; i++) {
        if(num & mask) {
            printf("1");
        } else {
            printf("0");
        }
        num <<= 1; // 左移一位
    }

    printf("\n");
}

int main() {
    int num = 10;
    printBinary(num);

    return 0;
}

In the above code, we have defined a function printBinary to output the binary representation of an integer. In the main function, we call this function and pass an integer 10 as a parameter. When the code is executed, it will output the binary representation of 10 as 00000000000000000000000000001010. You can modify the parameters and number of bits in the function according to your needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds