任務是從鍵盤讀取一個整數,將其轉換爲8個4位組,然後將每個位轉換爲一個十六進制數並逐一輸出。這必須通過使用位移來完成,而不是其他解決方案。移位練習
我的想法是使用一個帶4個掩碼的掩碼來選擇位組,然後將該組右移,刪除前面的零,並輸出十六進制數。
以下是我試圖接近這一點:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = input.nextInt();
System.out.println("Binary representation: " + Integer.toBinaryString(x));
System.out.println("Hexadecimal representatio1n: " + Integer.toHexString(x));
int mask = 15 << 28;
System.out.println(Integer.toBinaryString(mask));
int k = 28;
for (int i = 1; i <= 8; i++)
{
int result = mask & x;
//System.out.println(Integer.toBinaryString(result));
result = x >>> k ;
mask = mask >> 4;
k = k - 4;
System.out.println(Integer.toHexString(result));
}
}
輸出示例:
Enter an integer: 324234234
Binary representation: 10011010100110110101111111010
Hexadecimal representatio1n: 13536bfa
11110000000000000000000000000000
1
13
135
1353
13536
13536b
13536bf
13536bfa
爲什麼不能正常工作?
謝謝。
[家庭作業標籤已被棄用和刪除。](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially- depprecated) – Radiodef