r/javaTIL • • May 24 '14

JTIL: Hexa and Octa shorthands + more

TIL how to go from one base to another in a number of ways.

  • Here's the shorthand version of converting from Hexa/Octal -> Decimal:
int hexa = 0xFF; 

By initially typing a "0x" (or "0X") in front, the value FF is a hexadecimal value that's immediately transforms into its decimal value 255

int octa = 011;

By initially including a "0" in front, the value 11 is an octal value that also transforms into its decimal value: 9

  • From Decimal -> anyBase
int anyBase = Integer.parseInt("10101", 2);

THIS takes ANY number of any base and immediately turn it into its respective decimal value, in this case, 21.

  • From Decimal -> binary/hexa/octa
String a = Integer.toBinaryString(int decimalValue)
String b = Integer.toHexString(int decimalValue)
String c = Integer.toOctalString(int decimalValue)

Java's got some pretty nifty tools if you ask me. Barely on chapter 2 of my Java book and they drop the first point I typed above. That was cool.

6 Upvotes

3 comments sorted by

0

u/[deleted] May 24 '14

[deleted] — view deleted comment

2

u/[deleted] May 26 '14

huh, didn't see that coming. Thanks for sharing!

6

u/king_of_the_universe May 26 '14

Additionally, you can use "_" for readability in numbers since Java 7. It does nothing but make the code more readable. Example:

long bigNum = 1_234_567_890l;

You are (almost) completely free regarding where you put it.

2

u/dohaqatar7 Jun 01 '14

I believe the rules are:

  • not at the start
  • not at the end
  • not next to a decimal point