#include <stdio.h>
#include <stdint.h>
void binary(char *buff, const void *data, size_t size) {
if(!size) {*buff = '\0'; return;}
uint8_t byte = *(const uint8_t *)&data[size - 1];
for(size_t mask = 0x80; mask; mask >>= 1) {
*buff++ = mask & byte ? '1': '0';
}
binary(buff, data, size - 1);
}
int main(void) {
char buff[33];
int a = 0x12345678;
binary(buff, &a, sizeof(a));
puts(buff);
return 0;
}
#include <stdio.h>
#include <stdint.h>
void binary(char *buff, const void *data, size_t size) {
uint8_t byte = *(const uint8_t *)(data + size - 1);
for(size_t mask = 0x80; mask; mask >>= 1) {
*buff++ = mask & byte ? '1': '0';
}
if(size == 1) {*buff = '\0'; return;}
*buff++ = '_'; binary(buff, data, size - 1);
}
int main(void) {
// 7个'_'
// 1个'\0'
// sizeof(double) == 8
// 8 * 8 + 8 = 72
printf("sizeof(double) == %lu\n", sizeof(double));
char buff[72];
{
char data = 0x12;
binary(buff, &data, sizeof(data));
printf("char:\t%s\n", buff);
}
{
int data = 0x12345678;
binary(buff, &data, sizeof(data));
printf("int:\t%s\n", buff);
}
{
float data = 123.456;
binary(buff, &data, sizeof(data));
printf("float:\t%s\n", buff);
}
{
double data = 123.456789;
binary(buff, &data, sizeof(data));
printf("double:\t%s\n", buff);
}
return 0;
}
$ ./main
sizeof(double) == 8
char: 00010010
int: 00010010_00110100_01010110_01111000
float: 01000010_11110110_11101001_01111001
double: 01000000_01011110_11011101_00111100_00000111_11101110_00001011_00001011
$
|