在C位,我怎么访问底层位在C浮动? [英] Bits in C, how do I access the underlying bits in a C float?
本文介绍了在C位,我怎么访问底层位在C浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定两个浮点数A和B,这是命令行参数,我必须创建方法来做他们按位运算。包括与,或,非,异或,浮点除等等...
Given a two floating point Numbers A and B, which are command line arguments, I must create methods to do bitwise operations on them. Including And, Or, Not, xOr, floating Point addition etc...
我如何可以访问每一位使用C?我需要访问特定的1和0。任何想法如何?
How can I access each bit in C? I need to access the specific 1's and 0's. Any idea how?
推荐答案
下面是使用工会的例子,如基思建议。
Here's an example using unions, as Keith suggests.
/* -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;
}
}
编辑:改签署整数为无符号。
changed signed ints to unsigned.
这篇关于在C位,我怎么访问底层位在C浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文