3

I think understand what they fundamentally do - operate on bits (flip, shift, invert, etc...).

My issue is that I don't know when I'd ever need to use them, and I don't think I fully understand bits.

I know that there are 8 bits in a byte and I know that bits are either a 0 or 1. Now here is where I start to get confused... I believe data types define combinations of bits differently. So if I declare an int, 32 bits are set aside for numbers, if I declare a char, 8 bits are set aside and the bits for that data type define a letter.

Running with that idea, I did the following basic operation in java which confuses me:

int num = 00000010;
System.out.println(num);

This prints 8 and if I define num this way:

int num = 00000100;
System.out.println(num);

This prints 64

So to practice with bitwise operations (just for the hell of it) I tried this:

int num = 00000010 << 1;
System.out.println(num);

And it prints 16 where as I thought it would shift the bits by one to the left and print 64.

What is happening here, and when would I ever need to apply this method of manipulating bits?

1

1 Answer 1

8

You are accidentally specifying an octal literal when you specify a number with a leading zero.

00000010 => 1*8^1 + 0*8^0 => 8
00000100 => 1*8^2 + 0*8^1 + 0*8^0 => 64

The JLS, Section 3.10.1, describes octal and binary literals:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer.

You are bit-shifting your 8 by one to the left, effectively multiplying it by 2 to get 16. In bits:

00000100 => 00001000
(8 => 16)

Binary literals are expressed with leading 0b, e.g.:

0b000010 => 2
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for this answer, when would you ever need to do something like this?
Bit shift operators are equivalent to multiplying by 2^amount for << and dividing by 2^amount for >>.
Are you aware of anyone ever deliberately using octal notation in Java who would have been bothered by needing a different prefix? Java's borrowing of a leading zero as an octal prefix seems like an odd choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.