【发布时间】:2019-11-06 14:29:46
【问题描述】:
当我标准输入相同的整数时,如何将整数转换为与使用 read(0,buff,nbytes) 获得的缓冲区相同的值/编码字符?我正在尝试编写类似 read() 的东西,但使用整数数据代替读入缓冲区的文件描述符参数。
like_read(int data,void *buff,size_t nbytes);
它应该与 read() 类似,因为它应该读入缓冲区的值与 read(0,buff,nbytes) 从标准输入到其缓冲区的值相同。当我直接提供整数地址作为缓冲区而不首先使用 read(0,buff,nbytes) 时,例如
int Integer=25
int nbytes=2;
int rlen,wlen,wlen1;
int fd = open("ttyusb.txt", O_RDWR | O_CREAT,0777);
wlen = write(fd, &Integer, nbytes);
wlen1 = write(1, &Integer, nbytes);//for stdout
close(fd);
预期输出
25
实际输出/文件内容是一些编码字符
,它没有给我想要的结果,因为首先使用 read() 从 stdin 将整数读入缓冲区,然后使用 write() 将该缓冲区写入文件,例如:
int Integer;
int nbytes=2;
int rlen,wlen;
int fd = open("ttyusb.txt", O_RDWR | O_CREAT,0777);
rlen = read(0, &Integer, nbytes);
wlen = write(fd, &Integer, nbytes);
wlen1 = write(1, &Integer, nbytes);//for stdout
close(fd);
标准输入
25
预期输出
25
实际输出/文件内容
25
当我在读取(0,缓冲区,nbytes)之后打印缓冲区值时,它会给出一些编码值:
int Integer, nbytes=2;
int fd = open("ttyusb.txt", O_RDWR | O_CREAT,0777);
rlen = read(0, &Integer, nbytes);
wlen = write(fd, &Integer, nbytes);
wlen1 = write(1, &Integer, nbytes);
printf("\nInteger buffer value %d\n",Integer);
close(fd);
stdin 0 打印“整数缓冲区值 2608”,stdin 1 打印“整数缓冲区值 2609”,stdin 2 打印“整数缓冲区值 2610”,.....stdin 9 打印“整数缓冲区值 2617”...
read() 使用什么编码来转换整数值,我如何在没有 read() 的情况下进行转换?
【问题讨论】:
-
@user3121023 那么两位整数呢?比如 10 给出 12337、11 给出 12593、12 给出 12849...?
-
字符 '1'、'0' 的 ASCII 值分别为 0x31 和 0x30。如果您将其读取为 little-endian、2 字节整数,则该值将为 0x3031,即 12337。顺便说一下,
int的大小通常为 4 字节,如果变量在堆栈上并且没有已初始化,int的其他 2 个字节将是不确定的。 -
@IanAbbott 它不会像单个数字 1 0x0A31 ('1',LF) 那样捕获两位数的 LF 吗?为什么 10 不是 0x0A3031 ('1','0',LF)?
-
@Optic_Ray 如果不是 0x0A3031,因为您只读取 2 个字节。
标签: c linux encoding file-io format