Pergunta

I have this code:

char kbits[k]; long int bits;

The kbits string is always filled with '1', for example:

If k = 5, kbits = "11111"

If k = 9, kbits = "111111111"

To do this I use this code:

for(i = 0; i < k; i++) kbits[i] = '1';

And then I run:

bits = atoi(kbits);

So I have the integer of kbits, for example, if kbits = "1111", bits = 1111;

For k <= 10, it runs perfectly fine.

For k > 10 it puts a 7 in last position of kbits (for example, if k = 11, kbits = 11111111117) and bits = 2147483647 (this value is for any value of k, I think it is random?)

Foi útil?

Solução

atoi interprets its input as a decimal number, not a binary number. Your longer string is causing the value to overflow, in which case the return value of atoi is undefined (although returning INT_MAX is common, which is equal to the value you're seeing).

To interpret the input as a binary number you can use strtol like this:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>

int main()
{
    char line[256];

    while (printf("\nInput: "),
           fgets(line, sizeof line, stdin))
    {
        // skip initial whitespace and break if input is nothing but whitespace
        char *p = line;
        while (isspace(*p)) ++p;
        if (*p == '\0') break;

        // interpret input as a binary number    
        long n = strtol(line, &p, 2);

        if (p == line)
            printf("** Can't convert any characters. **\n");
        else if (n == LONG_MAX || n == LONG_MIN)
            printf("** Range error **\n");
        else
            printf("Value: %ld\n", n); // prints value in decimal

        while (isspace(*p)) ++p; // skip whitespace after the value
        if (*p != '\0')
            printf("** Excess characters in input **\n");
    }

    return 0;
}

Outras dicas

Your input is too large for the return type. Per the docs:

If the converted value cannot be represented, the behavior is undefined.

An int is a signed type of at least 16-bits. On your platform it may be 32-bits and, in that case, its max value is 2^31-1. Too small for your input of ~11 billion. Use strtol, which returns a long int, instead.

Also, make sure you're terminating that string.

2147483647 (this value is for any value of k, I think it is random?)

No, it is not random; it is the largest value a signed 32-bit integer can hold.

Your inputs are too big.

When this happens, the return value of atoi is undefined (per the documentation); the result you're seeing is common in practice.

Define kbits to be one byte longer then the number of 1s you want to store and do initialise it to all 0s.

#define K (5)
char kbits[K + 1] = ""; /* One more for the `0`temrination neseccary to terminate a C-"string". */
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top