Before Java 7, if you wanted to manipulate a binary value, you’d have had to either engage in awkward (and error-prone) base conversion or utilize parseX methods. For example, if you wanted to ensure that an int x represented the bit pattern for the decimal value 102 correctly, you’d write an expression like:
int x = Integer.parseInt("1100110", 2);
This is a lot of code just to ensure that x ends up with the correct bit pattern. There’sworse to come though. Despite looking fine, there are a number of problems with this approach:
■ It’s really verbose.
■ There is a performance hit for that method call.
■ You’d have to know about the two-argument form of parseInt().
■ You need to remember the details of how parseInt()behaves when it has
two arguments.
■ It makes life hard for the JIT compiler.
■ It represents a compile-time constant as a runtime expression, which means the
constant can’t be used as a value in a switch statement.
■ It will give you a RuntimeException (but no compile-time exception) if you
have a typo in the binary value.
Fortunately, with the advent of Java 7, we can now write this:
int x = 0b1100110;
No one’s saying that this is doing anything that couldn’t be done before, but it has none of the problems we listed. If you’ve got a reason to work with binary, you’ll be glad to have this small feature.For example, when doing low-level handling of bytes, you can now have bit patterns as binary constants in switch statements.
int x = Integer.parseInt("1100110", 2);
This is a lot of code just to ensure that x ends up with the correct bit pattern. There’sworse to come though. Despite looking fine, there are a number of problems with this approach:
■ It’s really verbose.
■ There is a performance hit for that method call.
■ You’d have to know about the two-argument form of parseInt().
■ You need to remember the details of how parseInt()behaves when it has
two arguments.
■ It makes life hard for the JIT compiler.
■ It represents a compile-time constant as a runtime expression, which means the
constant can’t be used as a value in a switch statement.
■ It will give you a RuntimeException (but no compile-time exception) if you
have a typo in the binary value.
Fortunately, with the advent of Java 7, we can now write this:
int x = 0b1100110;
No one’s saying that this is doing anything that couldn’t be done before, but it has none of the problems we listed. If you’ve got a reason to work with binary, you’ll be glad to have this small feature.For example, when doing low-level handling of bytes, you can now have bit patterns as binary constants in switch statements.
No comments:
Post a Comment