简体   繁体   中英

function doesn't return long long int

I don't know why my function doesn't give the correct result. I suspect that it doesn't return the right type (unsigned long long int), but it return an int instead.

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

// compile with:
//         gcc prog_long_long.c -o prog_long_long.exe
// run with:
//         prog_long_long

unsigned long long int dec2bin(unsigned long long int);

int main() {
    unsigned long long int d, result;

    printf("Enter an Integer\n");

    scanf("%llu", &d);

    result = dec2bin(d);

    printf("The number in binary is %llu\n", result);

    system("pause");

    return 0;
}

unsigned long long int dec2bin(unsigned long long int n) {
    unsigned long long int rem;
    unsigned long long int bin = 0;
    int i = 1;
    while (n != 0) {
        rem = n % 2;
        n = n / 2;
        bin = bin + (rem * i);
        i = i * 10;
    }
    return bin;
}

Here is the output of the result with different input values:

C:\Users\desktop\Desktop\gcc prog_long_long.c -o prog_long_long.exe

C:\Users\desktop\Desktop\prog_long_long
Enter an Integer
1023
The number in binary is 1111111111
The number in octal is 1777

C:\Users\desktop\Desktop\prog_long_long
Enter an Integer
1024
The number in binary is 1410065408
The number in octal is 2994

You cannot convert a number to binary this way, decimal and binary are external representations of the same number. You should convert the number as a C string, computing one binary digit at a time, from right to left.

Here is how it works for 64-bit long long ints:

#include <stdio.h>
#include <string.h>

char *dec2bin(char *dest, unsigned long long int n);

int main(void) {
    unsigned long long int d;
    char buf[65], *result;

    printf("Enter an Integer\n");

    if (scanf("%llu", &d) == 1) {
        result = dec2bin(buf, d);
        printf("The number in binary is %s\n", result);
    }

    //system("pause");

    return 0;
}

char *dec2bin(char *dest, unsigned long long int n) {
    char buf[65];
    char *p = buf + sizeof(buf);

    *--p = '\0';
    while (n > 1) {
        *--p = (char)('0' + (n % 2));
        n = n / 2;
    }
    *--p = (char)('0' + n);
    return strcpy(dest, p);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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