如何按位输出float数
请问大家如何按位输出float数 输出二进制 0000 0101 ... 那样的? *(int*)&f c_cpp_python 发表于 2022-3-2 12:20输出二进制 0000 0101 ... 那样的?
是的是的
#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;
for(size_t mask = 0x80; mask; mask >>= 1) {
*buff++ = mask & byte ? '1': '0';
}
binary(buff, data, size - 1);
}
int main(void) {
char buff;
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;
{
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
$ #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) {
{
char buff;
char data = 0x12;
binary(buff, &data, sizeof(data));
printf("char:\t%s\n", buff);
}
{
char buff;
int data = 0x12345678;
binary(buff, &data, sizeof(data));
printf("int:\t%s\n", buff);
}
{
char buff;
float data = 123.456;
binary(buff, &data, sizeof(data));
printf("float:\t%s\n", buff);
}
{
char buff;
double data = 123.456789;
binary(buff, &data, sizeof(data));
printf("double:\t%s\n", buff);
}
return 0;
}
本帖最后由 jhq999 于 2022-3-2 19:34 编辑
int main()
{
float f=1.234;
scanf("%f",&f);
int i = 0;
for(i=31;i>=0;i--)
{
printf("%d",((*(int*)&f)>>i)&1);
if (i%4==0)
printf(" ");
}
return 0;
}
页:
[1]