C语言 如何使用write()以十六进制形式写入指针地址的标准输出

w1e3prcc  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(121)

在一个任务中,我需要将一个十六进制的指针地址打印到标准输出中。问题是我只允许包含unistd.h,所以不允许printf
我试着把它转换成一个字符 *,但转换是相当不可能实现的。所以帮助将在这里非常感谢。
它应该输出这样的内容:

000000010a161f40

字符串

nhaq1z21

nhaq1z211#

下面是一个函数的例子,它可以做到这一点:

#include <unistd.h> // Prototype of write()

size_t my_putchar(char c) // Function for writing to standard output
{
    if (write(1, &c, 1) == -1)
        return (0); // Returns 0 because no char has been written
    return (1); // Returns 1 because a char has been written
}

size_t my_puthex(unsigned long long nb, short toUp)
{
    size_t len = 0;
    const char *base = (toUp == 1) ? "0123456789ABCDEF" : "0123456789abcdef"; // If toUp is 1, the letters will be displayed in uppercase, otherwise in lowercase.
    if (nb < 16) { // If the number is less than 16, simply write the corresponding char by calling `putchar()`
        len += my_putchar(base[nb]);
        return (len);
    } else { // Recursively call the puthex() function to write the characters 1 by 1.
        len += my_puthex(nb / 16, toUp);
        len += my_bputchar(base[nb % 16]);
    }
    return (len); // Returns the number of chars written
}

字符串
使用方法:

my_puthex(1724, 0); // Write 1724 in hexadecimal in lower case
my_puthex(1724, 1); // Write 1724 in hexadecimal in upper case


输出量:

6bc
6BC


但是,输入值必须是无符号整数。如果可以包含<stdbool.h>,也可以将toUp替换为bool。

8fsztsew

8fsztsew2#

还有这个

void ptr2hex( const void *ptr ) {
    unsigned long long val = (unsigned long long)ptr;
    char buf[ 2 * sizeof ptr ];
    size_t i = sizeof buf;

    for( ; i; val >>= 4 )
        buf[ --i ] = "0123456789abcdef"[ val & 0xF ];

    write( 1, buf, sizeof buf );
}

int main( void ) {
    ptr2hex( "" );

    return 0;
}

字符串
简单地说,long long的大小是8个字节,转换为16个ASCII数字。i被分配为8个字节的两倍。出现一个大小为8个字节的缓冲区,从它的 end 到它的 beginning,用16个ASCII数字循环填充。(前导零来自同一个源,对处理器来说只是稍微多一点的练习。)然后,简单地用一个write()按顺序输出这些数字。
三个变量,一个循环,没有递归。
有义务@chux指出一些代码调整。

lxkprmvk

lxkprmvk3#

我编写了一个print_pointer函数,它的功能与printf("%p",pointer)完全相同

#include <unistd.h>

void print_pointer(const void *p)
{
    static const char *table = "0123456789abcdef";
   unsigned long long value = (unsigned long long)p;
   // 1 digit = 4 bits
   char buffer[sizeof(void*)*2];
   int i,idx = 0;
   
   while(value)
   {
       int digit = value % 16;
       buffer[idx++] = table[digit];
       
       value /= 16;
   }
   // zero-padding
   for (i=idx;i<sizeof(buffer);i++)
   {
       buffer[i] = '0';
   }
   // reversed print, as division computes lowest digits first
   for (i=sizeof(buffer)-1;i>=0;i--)
   {
       write(1,buffer+i,1); // write 1 char to standard output
   }
   
    
}

int main()
{
    const char *data = "foo";
    
    print_pointer(data);
    
    return 0;
}

字符串

相关问题