Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned long hexadecimal representation

Tags:

c

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[256] = {};
    unsigned long i=13835058055298940928;
    snprintf(buf, 1024, "%lx", i); /* Line 7 */
    printf("%s\n",buf);
    return 0;
}

In line 7, if I use %lux, and then snprintf doesn't do any conversion. It just prints 0x13835058055298940928x, whereas if I use just %lx, it prints an expected hexadecimal conversion.

How do I represent unsigned long in hexadecimal?

like image 504
Shraddha Avatar asked Oct 20 '13 14:10

Shraddha


1 Answers

A format of "%lux" is treated as "%lu" (unsigned long, decimal) followed by a letter x.

The "%x" format requires an argument of unsigned type; there's no (direct) mechanism to print signed integers in hexadecimal format.

The format for printing an unsigned long value in hexadecimal is "%lx". (x is hexadecimal, d is signed decimal, u is unsigned decimal; any of them may be qualified with l for long.)

Note that the value 13835058055298940928 requires at least a 64-bit unsigned type to store it without overflow. The type unsigned long is at least 32 bits; it's 64 bits on some systems, but by no means all. If you want your code to be portable, you should use type unsigned long long rather than unsigned long. The format for printing an unsigned long long value in hexadecimal is "%llx".

For clarity, I usually precede hexadecimal output with 0x, so it's obvious to the reader that it's a hexadecimal number:

printf("0x%llx\n", some_unsigned_long_long_value);

(You can achieve the same result with %#llx, but I find it easier to write out 0x than to remember the meaning of the # flag.)

like image 144
Keith Thompson Avatar answered Nov 15 '22 22:11

Keith Thompson