0

Considering this simple example :

unsigned long long int my_int=0b10100110;
printf("%.64B\n",my_int<<40);

Why is the output zero ? unsigned long long int is used (sizeof = 8), 64 bits machine, OS : Fedora 37, gcc (GCC) 12.2.1 20221121 (Red Hat 12.2.1-4), and compilation with or without the m64 flag.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • 2
    My compiler doesn't accept the %B format specifier, but if I print in hex, it works: `a60000000000`. So the shift works, its the printf() that fails. @KamilCuk seems to have found the solution. – pmacfarlane Jan 12 '23 at 18:24
  • 9
    Have you seen the `warning: format ‘%B’ expects argument of type ‘unsigned int’, but argument 2 has type ‘long long unsigned int’` ? – KamilCuk Jan 12 '23 at 18:25
  • 1
    Perhaps, ```%B``` ---> ```%llu```. – Harith Jan 12 '23 at 18:29
  • 1
    Ok. %B accepts only 32 bits integers and not 64 bits. – Stef1611 Jan 12 '23 at 18:52
  • 1
    Not aware of `%B` – is that standard at all? If it follows the usual pattern of other format specifiers you might try `%llB` to indicate `unsigned long long` to the compiler... – Aconcagua Jan 12 '23 at 18:55
  • @Aconcagua. Thanks a lot. This is the solution. To complete your comment : `.64llB`, to have leading 0. – Stef1611 Jan 12 '23 at 19:01
  • @Aconcagua `"%B"` is not standard. Perhaps in upcoming C2x. – chux - Reinstate Monica Jan 12 '23 at 19:08
  • @Stef1611 Ref: print in [binary](https://stackoverflow.com/q/111928/2410359) (or using standard C in [any base](https://stackoverflow.com/a/34641674/2410359)). – chux - Reinstate Monica Jan 12 '23 at 20:13

1 Answers1

3

For starters this format of an integer constant

0b10100110

is not standard.

Binary integer constants are valid in C++.

Also the function printf does not support the conversion specifier B.

In any case to output an object of the type unsigned long long int you need to use length modifier ll before the conversion specifier.

Instead you could use a hexadecimal integer constant like for example

unsigned long long int my_int = 0xA6;

and output it like

printf("%#.8llx\n",my_int<<40);

In this case the output will look like

0xa60000000000

Or as @chux - Reinstate Monica correctly pointed in the comment to the answer you can use the following call

printf("%#0.8llx\n",my_int<<40);

to output the prefix 0x when the corresponding argument is equal to 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335