0

How Can I solve this problem in java ?

int mask = ~0;

System.out.println(Integer.toBinaryString(mask));

When I type this, the output becomes: 11111111111111111111111111111111 However I just want to get 8 bits (11111111).

Another example is,

int left = mask << 7;

System.out.println(Integer.toBinaryString(left));

Output of these two lines is: 11111111111111111111111110000000 How can I take the last 8 bit ? (10000000).

2

1 Answer 1

1

The type int has 4 bytes,every byte has 8 bits,so when you call toBinaryString of Integer class,you get 32 bit String.

You can use code below to achieve your goal.

int mask = ~0;
System.out.println(Integer.toBinaryString(mask & 0xFF));
int left = mask << 7;
System.out.println(Integer.toBinaryString(left & 0xFF));

I hope the code will help you.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.