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)
",sizeof(struct bs));
bit.a = 4;
bit.b = 1;
bit.c = 34235;
printf("a: %d b: %d c: %d
", bit.a, bit.b, bit.c);
return 0;
}