逻辑运算后十六进制转bin
我想要:
111 || 100 ---> 111, not 1
100 && 100 ---> 100, not 1
101 && 010 ---> 000, not 0
损坏的代码
#include <stdio.h>
main(void){
string hexa = 0xff;
strig hexa2 = 0xf1;
// CONVERT TO INT??? cast
int hexa3 = hexa || hexa2;
int hexa4 = hexa && hexa2;
puts(hexa3);
puts(hexa4);
}
I want:
111 || 100 ---> 111, not 1
100 && 100 ---> 100, not 1
101 && 010 ---> 000, not 0
Broken code
#include <stdio.h>
main(void){
string hexa = 0xff;
strig hexa2 = 0xf1;
// CONVERT TO INT??? cast
int hexa3 = hexa || hexa2;
int hexa4 = hexa && hexa2;
puts(hexa3);
puts(hexa4);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要按位运算符(
|
、&
)而不是逻辑运算符(||
、&&):
对于损坏的代码,您的
hexa
和hexb
类型也不正确,它们都应该是数字类型:最后,要输出整数,您可以使用
printf
来格式化它们:You want the bitwise operators (
|
,&
) instead of the logical operators (||
,&&
):As for your broken code, you also have incorrect types for
hexa
andhexb
which should both be numeric types:Finally, to output an integer, you would use
printf
to format them:string
在这里不是正确的数据类型。数字 0xff(二进制为 11111111)和字符串“0xff”之间存在很大差异。我假设你想处理前者;将字符串解析为整数本身就是一个完整的主题。对于 16 位序列来说,一种好的数据类型是unsigned int
。旁注:即使对于布尔值,||和|是不同的,因为短路:当你有一个 || 时b,仅当 a 为 false 时才计算 b。两个参数均针对
a | 求值b.
。这很重要,即当两个操作数之一是具有副作用的函数调用时。string
is not the right data type here. There is a big difference between the number 0xff (which is 11111111 in binary) and the string "0xff." I'm assuming you want to deal with the former; parsing strings into integers is an entire topic of its own. One good data type for a sequence of 16 bits isunsigned int
.Side note: even for booleans, || and | are different, because of short-circuiting: when you have
a || b
, b is only evaluated if a is false. Both arguments are evaluated fora | b
. This matters, i.e., when one of the two operands is a function call with side-effects.