C언어에서 float, double 형 2진수로 출력하기

mhComa·2021년 8월 2일
0

공용체를 이용한다.

#include <stdint.h>
#include <stdio.h>

typedef union v32_union {
	float f;
	uint32_t u;
} v32;

typedef union v64_union {
	double f;
	uint64_t u;
} v64;

void print_float_bits (float f) {
	v32 v; v.f = f;
	uint32_t mask = 1 << 31;
	do {
		if (mask == 0x40000000 || mask == 0x400000) putchar(' ');
		putchar(v.u & mask ? '1' : '0');
	} while (mask >>= 1);
}

void print_double_bits (double d) {
	v64 v; v.f = d;
	uint64_t mask = 1ULL << 63;
	int count = 63;
	do {
		if (mask == 0x4000000000000000 || mask == 0x8000000000000) putchar(' ');
		putchar(v.u & mask ? '1' : '0');
		count--;
	} while (mask >>= 1);
}

int main(void) {
	float a = 3.1415926f;
	double b = 3.141592653589793238;

	print_float_bits(a); /* 0 10000000 10010010000111111011010 */
	putchar('\n');
	print_double_bits(b); /* 0 10000000000 1001001000011111101101010100010001000010110100011000 */
}
profile
Ich bin ein Hund!

0개의 댓글