首页 / C++ / C++中的补码公式与位域
C++中的补码公式与位域
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++中的补码公式与位域,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2417字,纯文字阅读大概需要4分钟。
内容图文
![C++中的补码公式与位域](/upload/InfoBanner/zyjiaocheng/645/7394e0894b6040d8b7f10ad7edf2fbef.jpg)
C++中的补码公式与位域:
代码很简单就不多说:
补码公式:
#include <iostream>
using namespace std;
void operator_1(void);
void operator_2(void);
void operator_3(void);
int main(void) {
/*
-x = ~x+1 = ~(x-1)
~x = -x-1
-(~x) = x+1
~(-x) = x-1
x+y = x - ~y-1 = (x|y) + (x&y)
x-y = x + ~y+1 = (x|~y) - (~x&y)
x^y = (x|y) - (x&y)
x|y = (x& ~y) + y
x&y = (~x|y) - ~x
x==y : ~(x-y|y-x)
x!=y : x-y|y-x
x<y : (x-y) ^ ((x^y) & ((x-y) ^x))
x<=y : (x|~y) & ((x^y) | ~(y-x))
x<y : (~x&y) | ((~x|y) & (x-y)) //unsigned
x<=y : (~x|y) & ((x^y) | ~(y-x)) //unsigned
*/
operator_1();
operator_2();
operator_3();
return 0;
}
void operator_1(void) {
int x = 1;
cout << "-x = " << -x << " ~x+1 = " << ~x + 1 << endl;
cout << "~x = " << ~x << " -x-1 = " << -x - 1 << endl;
cout << "-(~x) = "<< -(~x) << " x+1 = " << x + 1 << endl;
cout << "-(~x) = "<< -(~x) << " x-1 = " << -x -1 << endl;
}
void operator_2(void) {
int x = 3, y = 5;
cout << endl;
cout << "x: " << x << "y: " << y << endl;
cout << "x+y=" << x+y << " x- ~y-1= " << x - ~y - 1
<< " (x|y)+(x&y) = " << (x|y) + (x&y) << endl;
cout << "x-y=" << x-y << " x+ ~y+1= " << x + ~y + 1
<< " (x|~y) - (~x&y) = " << (x|~y) - (~x|y) << endl;
cout << "x^y=" << (x^y) << " (x|y) - (x&y)" << (x|y) - (x&y) << endl;
cout << "x|y=" << (x|y) << " (x& ~y) + y = " << (x& ~y) + y << endl;
cout << "x&y=" << (x&y) << " (~x|y) - ~x = " << (~x|y) - ~x << endl;
}
void operator_3(void) {
int x = -3, y = -5;
unsigned int x_t = -1, y_t = -5;
cout << "x: " << x << "y: " << y << endl;
cout << "x==y =" << (x==y) << " ~(x-y|y-x) =" << ~(x-y|y-x) << endl;
cout << "x!=y =" << (x!=y) << " x-y|y-x =" << (x-y|y-x) << endl;
cout << "x<y =" << (x<y) << " (x-y) ^ ((x^y) & ((x-y)^x))=" << ((x-y) ^ ((x^y) & ((x-y)^x))) << endl;
cout << "x<=y =" << (x<=y) << " (x|~y) & ((x^y) |~ (y-x))=" << ((x|~y) & ((x^y) |~ (y-x))) << endl;
cout << "unsigned: x<y =" << (x_t<y_t)
<< " (~x&y) | ((~x|y) & (x-y))" << ((~x_t&y_t) | ((~x_t|y_t) & (x_t-y_t))) << endl;
cout << "unsigned: x<=y =" << (x_t<=y_t)
<< " (~x|y) & ((x^y) | ~(y-x) =" << ((~x_t|y_t) & ((x_t^y_t) |~ (y_t-x_t))) << endl;
}
位域
#include <stdio.h>
typedef struct bs {
int a:2;
int b:1;
int c:12;
unsigned d:4
}bs;
struct bit_2 {
unsigned a:2;
unsigned :2; //It can't use
unsigned :0; //NULL
unsigned b:4;
unsigned c:4;
};
int main(void) {
bs bit;
printf("sizeof(%d) \n",sizeof(struct bs));
bit.a = 4;
bit.b = 1;
bit.c = 34235;
printf("a: %d b: %d c: %d\n", bit.a, bit.b, bit.c);
return 0;
}
内容总结
以上是互联网集市为您收集整理的C++中的补码公式与位域全部内容,希望文章能够帮你解决C++中的补码公式与位域所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。