// Trying an obsolete GNU printf extension.
#include <limits.h>
#include <stdio.h>
#include <printf.h>
#define BITS(x) (sizeof(x) * CHAR_BIT)
#define MIN(a, b) \
({ __auto_type _x = (a); __auto_type _y = (b); \
(_y < _x) ? _y : _x; })
#define MAX(a, b) \
({ __auto_type _x = (a); __auto_type _y = (b); \
(_y > _x) ? _y : _x; })
int fillc(int c, int n, FILE *stream)
{
int result = 0;
for (int i = 0; i < n && result != EOF; i++)
result
= fputc(c
, stream
); return result;
}
int bitlimit(const struct printf_info *info)
{
if (info->is_char)
return BITS(char);
if (info->is_short)
return BITS(short);
if (info->is_long)
return BITS(long int);
if (info->is_long_double)
return BITS(long long int);
return BITS(int);
}
int bitlength(unsigned long long int x)
{
return BITS(x) - __builtin_clzll(x | 1);
}
int print_binary(FILE *stream, const struct printf_info *info, const void *const *args)
{
unsigned long long int value = *(const unsigned long long int *) args[0];
int width = info->width;
int count = MIN(bitlength(value), bitlimit(info));
if (!info->left)
fillc(info->pad, width - count, stream);
for (int i = count-1; i >= 0; i--)
fputc(((value
>> i
) & 1) + '0', stream
); if (info->left)
fillc(info->pad, width - count, stream);
return MAX(width, count);
}
int print_binary_arginfo(const struct printf_info *info, size_t n, int *argtypes)
{
if (n > 0)
argtypes[0] = PA_INT | PA_FLAG_LONG_LONG;
return 1;
}
int main(void)
{
register_printf_function('B', print_binary, print_binary_arginfo);
for (int i = 0; i < 16; i++) {
printf("<%8B>; <%-8B>; <%08B>; <%B>\n", i
, i
, i
, i
); }
const char *format[] = {
"<%hhB>\n", "<%hB>\n", "<%B>\n", "<%lB>\n", "<%llB>\n", 0};
for (const char **p = format; *p != 0; p++) {
}
return 0;
}
Ly8gVHJ5aW5nIGFuIG9ic29sZXRlIEdOVSBwcmludGYgZXh0ZW5zaW9uLgoKI2luY2x1ZGUgPGxpbWl0cy5oPgojaW5jbHVkZSA8c3RkaW8uaD4KI2luY2x1ZGUgPHByaW50Zi5oPgoKI2RlZmluZSBCSVRTKHgpIChzaXplb2Yoe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