class BitOperation
{
public static void main(String[] args)
{
if (args.length==0 || args==null)
{
PrintBin(-128);
return;
}
else
{
byte testByte;
testByte = Byte.parseByte(args[0]);
PrintBin(testByte);
}
}
static void PrintBin(byte i)
{
System.out.print("byte:"+i+" , binary:");
for(int j=7;j>=0;j--)
if (((i<<j)&i)!=0)
{
System.out.print("1");
}
else
{
System.out.print("0");
}
System.out.println();
}
}我用这段代码来求二进制码,
正数是对的,
为什么负数都是显示11111111????
{
public static void main(String[] args)
{
if (args.length==0 || args==null)
{
PrintBin(-128);
return;
}
else
{
byte testByte;
testByte = Byte.parseByte(args[0]);
PrintBin(testByte);
}
}
static void PrintBin(byte i)
{
System.out.print("byte:"+i+" , binary:");
for(int j=7;j>=0;j--)
if (((i<<j)&i)!=0)
{
System.out.print("1");
}
else
{
System.out.print("0");
}
System.out.println();
}
}我用这段代码来求二进制码,
正数是对的,
为什么负数都是显示11111111????
反码:101111111
补码:110000000
(最高位师符号位)
-128超出-127--127(一个字节)
所以要用第九位记符号位。你的程序有问题: static void PrintBin(byte i)
{
System.out.print("byte:"+i+" , binary:");
for(int j=7;j>=0;j--)
if (((i<<j)&i)!=0) //i移位了又和i作&运算回出错
{
System.out.print("1");
}
else
{
System.out.print("0");
}
System.out.println();
}
可以用以下方法:
...for (int j=15;j>+0;j--)
if (((1<<j)&i)!=0)
System.out.print("1")
else
System.out.print("0");
1:0000000000000001
(1<<15)-->:1000000000000000
(1<<14)-->:0100000000000000
(1<<13)-->:0010000000000000
这样可防止i的移位而造成错误,用1的移位去做&运算
但是我不同意你关于-128在JAVA中的二进 自码是9位的说法
我坚持是10000000(7个0)
我在WWW。JAVAUNION。ORG JAVA COLUMN上有详细的说明,
谢谢各位的参与和帮助。