c - C 中的位,如何访问 C float 中的底层位?

标签 c bit-shift

给定两个 float A 和 B,它们是命令行参数,我必须创建方法来对它们进行按位运算。包括 And、Or、Not、xOr、浮点加法等...

如何访问 C 中的每一位?我需要访问特定的 1 和 0。知道怎么做吗?

最佳答案

这是一个使用 union 的示例,正​​如 Keith 所建议的那样。


/* -std=c99 */
#include <stdio.h>

int main(int argc, char * argv[]) {

  /* note, I'm assuming an int has the same size of a float here */
  assert( sizeof(unsigned int) == sizeof(float) );

  union {
    float floating;
    unsigned int integer;
  } a;

  a.floating = 3.14;

  /* prints the bits in reverse order */
  unsigned int temp = a.integer;
  for( int i = 0; i < sizeof(float)*8; i++ ) {
    printf("%d", temp & 0x1);
    temp = temp >> 1;
  }
}

编辑:将有符号整数更改为无符号整数。

关于c - C 中的位,如何访问 C float 中的底层位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9401726/

相关文章:

c - 实现以下函数,将 float 的字符串表示形式转换为 double :

c - 从库中公开日志记录接口(interface)

c++ - 为什么我使用移位运算符 (C++) 得到随机结果?

c++ - 左移带有可变误差

c - '0'字符和<<运算符在本程序中的重要性

c - APU 上的 OpenCL 是否能够使用整个内存?

C gperftools - 分析 C 代码

c - 使用AVX512或AVX2最快的方法来计算所有打包的32位整数的和

C - 按位连接导致信息丢失

ARGB 到 RGBA 数组转换的 JavaScript 优化版本