我有以下 C 代码:
#include<stdio.h>
#include<unistd.h>
#include <arpa/inet.h>
int main()
{
uint32_t input;
read(0, &input, 4);
printf("%d",input);
return 0;
}
当我输入 1234 时,我希望它打印 1234 作为返回,但我得到的却是 875770417
如果我有一个不可更改的程序:
#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;
}
如何到达打印语句?因为输入246不行。
最佳答案
875770417
在字面上与 1234
完全相同,如果您将此数字解释为小端字节数的话。下面是一些显示此内容的快速 Python 代码:
>>> (875770417).to_bytes(4, 'little')
b'1234'
The read
syscall将读取您输入的原始字节:
ssize_t read(int fd, void *buf, size_t count);
read()
attempts to read up tocount
bytes from file descriptorfd
into the buffer starting atbuf
.
您输入了以下字节:
49, 50, 51, 52
...string 1234
的 ASCII 码。
您需要将此字符串转换为整数,但首先将此字符串读入某个缓冲区:
char buffer[64] = {0};
read(0, buffer, 4);
然后使用atoi
解析buffer
中的字符串并转换为整数:
$ 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'
$
关于c - 如何将输入从 read() 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61088388/