需求:将0xFD67转换为-665
1、语言:C
#include <stdio.h>
int main(int argc, char *argv[]) {
int a = 0xFD67;
printf("a=%d\n", a);
//清除符号位
int b = a & 0x7FFF;
printf("b=%d\n", b);
//反码
int c = ~b;
printf("c=%d\n", c);
//清除左边多余位
int d = c & 0x7FFF;
printf("d=%d\n", d);
//加1
d = d + 1;
//符号位
int e = d * -1;
printf("e=%d\n", e);
return 0;
}
结果:
a=64871
b=32103
c=-32104
d=664
e=-665
2、语言:java
public class Msbbit {
public static void main(String[] args) {
int a = 0xFD67;
System.out.println("a=" + a + " (0x" + Integer.toHexString(a).toUpperCase() + ")");
int b = a & 0x7FFF;
System.out.println("b=" + b + " (0x" + Integer.toHexString(b).toUpperCase() + ")");
int c = ~b;
System.out.println("c=" + c);
int d = c & 0x7fff;
System.out.println("d=" + d);
int e = d + 1;
System.out.println("e=" + e);
int f = e * -1;
System.out.println("f=" + f);
}
}
结果:
a=64871 (0xFD67)
b=32103 (0x7D67)
c=-32104
d=664
e=665
f=-665
3、语言:delphi
function NegativetoInt(const s: Integer): Integer;
var
a: Integer;
b: Integer;
c: Integer;
d: Integer;
begin
a := s and $7FFF;
b := not a;
c := b and $7FFF;
d := c + 1;
Result := d * -1;
end;
~~~~~~~~~~~~~~~
do one thing, do it better