Domanda

The task is to read an integer from keyboard, convert it into 8 groups of 4 bits, then convert each bit into a hex number and output them one after one. This must be done by using bit shifting, no other solution counts.

My idea was to use a mask with 4 ones to select the group of bits, then shift that group right, removing preceding zeroes, and output the number in hex.

Here's how I tried to approach this:

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));
    }
    }

Sample output:

Enter an integer: 324234234
Binary representation: 10011010100110110101111111010
Hexadecimal representatio1n: 13536bfa
11110000000000000000000000000000
1
13
135
1353
13536
13536b
13536bf
13536bfa

Why is it not working correctly?

Thanks.

È stato utile?

Soluzione

Your when you shift the result variable, you aren't shifting by the result, you are shifting it by x

if you change it to

result = result >>> k;

it should work

on a side note, this problem is much easier done the other way(from the least significant bit to the most significant bit) like

int x = 0xaabcdabcd;
int mask = 0x0fffffff;
for(int i =0;i < 8; i ++){
    System.out.println(x & mask);
    x = x >>> 4;
}

Altri suggerimenti

Because there are no unsigned types in Java, on line int mask = 15 << 28; you practically make your mask negative by moving bits up to sign field. Later you move it left with mask = mask >> 4; and thus carry down the sign bit. After the shift, your mask is not 00001111000000000000000000000000 but 11111111000000000000000000000000. Use logical right shift operator >>> instead.

PS. This seems like a homework. In such cases, one who asks question should mark the question with homework tag.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top