打印每一个bit位

本文介绍了如何通过不同的方法打印出浮点数的每一位,包括直接输出内存位、转换为16进制后手动转二进制,以及使用位运算的方式。这些方法可以避免精度丢失,允许灵活地控制输出位数,并能应用于不同长度的数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://stackoverflow.com/questions/1697425/how-to-print-out-each-bit-of-a-floating-point-number

1 直接将内存中的位输出了

每个输出一个char,然后输出为16进制。

还是么有二进制,自己再把16进制转换为2进制吧。

static void printme(void *c, size_t n)
{
  unsigned char *t = c;
  if (c == NULL)
    return;
  while (n > 0) {
    --n;
    printf("%02x", t[n]);
  }
  printf("\n");
}

void fpp(float f, double d)
{
  printme(&f, sizeof f);
  printme(&d, sizeof d);
}

 

 2

float myfloat = 254940.4394f;
printf("0x%p", *(void**)(&myfloat));

3 自己转换,没有精度丢失

#include <stdio.h>
#include <stdlib.h>

void output_binary_fp_number(double arg)
{
    double pow2;

    if ( arg < 0 ) { putchar('-'); arg = -arg; }
    if ( arg - arg != 0 ) {
        printf("Inf");
    }
    else {
        /* compare and subtract descending powers of two, printing a binary digit for each */
        /* first figure out where to start */
        for ( pow2 = 1; pow2 * 2 <= arg; pow2 *= 2 ) ;
        while ( arg != 0 || pow2 >= 1 ) {
            if ( pow2 == .5 ) putchar('.');
            if ( arg < pow2 ) putchar('0');
            else {
                putchar('1');
                arg -= pow2;
            }
            pow2 *= .5;
        }
    }

    putchar('\n');

    return;
}

void usage(char *progname) {
    fprintf(stderr, "Usage: %s real-number\n", progname);
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
    double arg;
    char *endp;

    if ( argc != 2 ) usage(argv[0]);
    arg = strtod(argv[1], &endp);
    if ( endp == argv[1] || *endp ) usage(argv[0]);

    output_binary_fp_number(arg);

    return EXIT_SUCCESS;
}

 5 位运算方式

#define IsBitSet(val, bit) ((val) & (1 << (bit)))

/* ... your code ... */

printf ("%c", IsBitSet(bit, 0) ? '1' : '0');
void    print_bits(unsigned char octet)
{
    int z = 128, oct = octet;

    while (z > 0)
    {
        if (oct & z)
            write(1, "1", 1);
        else
            write(1, "0", 1);
        z >>= 1;
    }
}

Including limits.h for CHAR_BIT, allows you to generalize the funciton to allow passing values of any length but limiting the the output to the number of bytes desired. Passing the file descriptor will allow writing to any open descriptor (or simply passing STDOUT_FILENO to write to stdout.

void writebits (const unsigned long v, int fd)
{
    if (!v)  { putchar ('0'); return; };

    size_t sz = sizeof v * CHAR_BIT;
    unsigned long rem = 0;

    while (sz--)
        if ((rem = v >> sz))
            write (fd, (rem & 1) ? "1" : "0", 1);
}

For example:

#include <stdio.h>
#include <unistd.h>

/* CHAR_BIT */
#ifndef CHAR_BIT
# define CHAR_BIT  8
#endif

void writebits (const unsigned long v, int fd)
{
    if (!v)  { putchar ('0'); return; };

    size_t sz = sizeof v * CHAR_BIT;
    unsigned long rem = 0;

    while (sz--)
        if ((rem = v >> sz))
            write (fd, (rem & 1) ? "1" : "0", 1);
}

int main (void) {

    unsigned v = 0xcafebabe;

    writebits (v, STDOUT_FILENO);
    putchar ('\n');
    writebits ((unsigned char)(v >> 24), STDOUT_FILENO);
    putchar ('\n');

    return 0;
}

Example Output

$ ./bin/writebits
11001010111111101011101010111110
11001010

 

 

If you want to print bits then used bitwise operator and you can do that...

such example:

for(i=31 ; i>=0 ; i--)
{
  if(num & 1<< i) /* num & 1 << position
   printf("1 ");
  else 
   printf("0 ");
}
printf("\n");

 

void print_bits(int n,unsigned int num)
{
   if(n == 31) return;
   print_bits(n+1,num);
   (num & (1<<n)) ? printf("1"):printf("0");    
}

void countBits(int n,unsigned int num)
{
    if(n == 31) return;

    countBits(n+1,num);
    if(num & (1<<n))
    {
       countOne++;
    }
   else
   {
      if(countOne)
         countZero++;
   }
}

void printbits(int num)
{
    printf("%d : ",num);
    print_bits(-1,num); 
    printf("\n");
    countBits(-1,num);
    printf("\n");
}

int main()
{
    printbits(189);
    printf("NumberOf1's[%d] Numberof0's[%d]\n",countOne,countZero);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值