简体   繁体   English

在C中写一个2位数的整数,仅包括<unistd.h>

[英]Write a 2 digit int in c including only <unistd.h>

Assuming I don't have access to any C standard libraries I'm trying to print a 2 digit int using the write(x, x, x) function. 假设我无权访问任何C标准库,我试图使用write(x,x,x)函数打印2位整数。 I have only included <unistd.h> as per specifications. 根据规范,我仅包含<unistd.h> My current function gives me only the ASCII representation of the value I pass into it. 我当前的函数只给我传递给它的值的ASCII表示。

void my_print(int x)
{
  write(1, &x, 2);
}

Use mod % and div to get upper and lower digit 使用mod%和div获取上下位数

int low = x%10;
int high = x/10; // could also have a sanity check for the range here

Then transform it to ascii by adding '0' 0x30 and write 然后通过添加“ 0” 0x30将其转换为ascii并写入

putchar(high+'0'); // Let compiler transform to char 
putchar(low+0x30); // Or this if you trust magic constants more

From here it is easy to transform the code to use write function 从这里很容易将代码转换为使用写入功能

#include <unistd.h>

void myprint(int x){
   char buf[]= {'0'+(x/10)%10, '0'+x%10};
   write(1,buf,2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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