How to convert input from read() to int

Viewed 202

I have following C code:

#include<stdio.h>
#include<unistd.h>
#include <arpa/inet.h>

int main()
{
        uint32_t input;
        read(0, &input, 4);
        printf("%d",input);
        return 0;

}

when I enter 1234 I expect it to print 1234 in return but instead I get 875770417

also if I have a non changeable program:

#include<stdio.h>
#include<unistd.h>
#include <arpa/inet.h>
int main()
{
        uint32_t a=123;
        uint32_t b=123;
        uint32_t sum=a+b;
        uint32_t input;
        read(0, &input, 4);
        if(sum == input)
                printf("Done\n");
        return 0;

}

How can I reach the print statement? Because inputting 246 doesnt work.

3 Answers

875770417 is quite literally the same as 1234 if you interpret this number as bytes in little endian. Here's some quick Python code that shows this:

>>> (875770417).to_bytes(4, 'little')
b'1234'

The read syscall will read the raw bytes that you input:

ssize_t read(int fd, void *buf, size_t count);

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

You inputted the following bytes:

49, 50, 51, 52

...which are the ASCII codes of the string 1234.

You need to convert this string to an integer, but first of all read this string into some buffer:

char buffer[64] = {0};
read(0, buffer, 4);

And then use atoi to parse the string in buffer and convert it to an integer:

$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    char buffer[64] = {0};
    uint32_t input;

    read(0, buffer, 4);
    input = atoi(buffer);

    printf("You entered: '%d'\n", input);
}
$ clang test.c && ./a.out
1234
You entered: '1234'
$ 

When you type '1 2 3 4 [Enter]', read() interprets it as the characters '1', '2,' '3' and '4' followed by a new-line. That is, printing each byte as an integer would probably yield 49, 50, 51, 52, 10: the ASCII value of each character. The more correct way would be to make an array of chars, read into it, and then use a string-to-int conversion function like atoi() or (better) strtol(). Example:

int main(void)
{
    char arr[6];
    read(0, arr, 6);
    long res = strtol(arr, NULL, 10);
    printf("%d", res);
}
#include <stdio.h>
#include <stdlib.h>

int main(void){
    char b[5];
    scanf("%s", b);
    int c=0;
    char *pb=&b[0];
    c=atoi(pb);
    printf("%d\n", c);
    system("pause");
}
Related