我正在使用一个函数(从 http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/ 借用代码)将 float 转换为二进制;存储在一个字符中。不过,我需要能够对结果执行按位运算,所以我一直在尝试找到一种方法来获取字符串并将其转换为整数,以便我可以根据需要移动位。我试过 atoi() 但它似乎返回 -1。
到目前为止,我有:
char binStringRaw[FP2BIN_STRING_MAX];
float myfloat;
printf("Enter a floating point number: ");
scanf("%f", &myfloat);
int castedFloat = (*((int*)&myfloat));
fp2bin(castedFloat, binStringRaw);
其中输入为“12.125”,binStringRaw 的输出为“10000010100001000000000000000000”。但是,尝试对此执行按位运算会出现错误:“二进制表达式的操作数无效('char[1077]' 和 'int')”。
附言- 如果这是一个简单的问题或者我的代码存在一些一般性问题,我深表歉意。我对来自 Python 的 C 编程非常陌生。
最佳答案
“castedFloat 已经是 float 的二进制表示,因为强制转换操作告诉它将 myfloat 的位解释为整数位而不是 float 。”
编辑感谢Eric Postpischil :
Eric Postpischil in Comments: "the above is not guaranteed by the C standard. Dereferencing a converted pointer is not fully specified by the standard. A proper way to do this is to use a union:
int x = (union { float f; int i; }) { myfloat } .i;
. (And one must still ensure that int and float are the same size in the C implementation being used.)"
位运算只定义为整数类型的值,例如 char、int、long、...,这就是为什么在字符串(字符数组)上使用它们时会失败的原因
顺便说一句,
int atoi(char*)
返回写在该字符串中的数字的整数值,例如。
atoi("12")
将返回值为 12 的整数
如果你想转换存储在字符串中的二进制表示,你必须逐位设置与字符对应的整数,执行此操作的函数可能如下所示:
long intFromBinString(char* str){
long ret=0; //initialize returnvalue with zero
int i=0; //stores the current position in string
while(str[i] != 0){ //in c, strings are NULL-terminated, so end of string is 0
ret<<1; //another bit in string, so binary shift resutl-value
if(str[i] == '1') //if the new bit was 1, add that by binary or at the end
ret || 0x01;
i++; //increment position in string
}
return ret; //return result
}
函数fp2bin需要获取一个double作为参数。如果您使用 castedFloat 调用它,(现在解释为整数)值将被隐式转换为 float ,然后传递给它。
我假设您想获得 float 的二进制表示,对其进行一些按位运算,然后将其传递。 为了做到这一点,你必须将它转换回 float ,与你之前做的相反,所以
int castedFloat = (*((int*)&myfloat));
{/*** some bitwise magic ***/}
float backcastedFloat = (*(float*)&castedFloat);
fp2bin(castedFloat, binStringRaw);
编辑:(再次感谢 Eric):
union bothType { float f; int i; }) both;
both.f = myfloat;
{/*** some bitwise magic on both.i ***/}
fp2bin(both.f, binStringRaw);
应该可以
关于C - 将 char 转换为 int 以对输出执行按位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191664/