繁体   English   中英

c 格式输入到二进制然后 output

[英]c format input to binary and then output

我想使用以下代码获取用户输入:

uint32_t value;
printf("value: ");
scanf("%"SCNu32, &value);

我现在的问题是,我将如何使用用户输入(在我的情况下为值),然后将其格式化为二进制数,在 function print_binary 中没有循环? output 必须在 0b 之后 32 位。 我不能在任何地方使用任何类型的循环。

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

void print_binary(uint32_t value){

    printf("%d = 0b",value);
    //I want to print the variable value with a fixed length of 32 and that it is 
    //binary with the starting index of 0bBinaryValueOfNumber.
    return;
}

int main(void) {
    uint32_t value;
    printf("value: ");
    if (scanf("%"SCNu32, &value) != 1) {
        fprintf(stderr, "ERROR: While reading the 'uint32_t' value an error occurred!");
        return EXIT_FAILURE;
    }
    printf("\n");
    print_binary(value);
    printf("\n");
    return EXIT_SUCCESS;
}

我也有以下例子:

如果用户输入为 5,则 function 应返回“5 = 0b00000000000000000000000000000101”。

如果你不能使用循环,你可以使用递归:

void print_bin(uint32_t n, int digits) {
    if (digits > 1) print_bin(n >> 1, digits - 1);
    putchar('0' + (n & 1));
}

void print_binary(uint32_t value) {
    printf("%d = 0b", value);
    print_bin(value, 32);
    printf("\n");
}

使用尾递归的替代方法:

void print_bin(uint32_t n, int digits) {
    putchar('0' + ((n >>-- digits) & 1));
    if (digits > 0) print_bin(n, digits);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM