0
 int hexNumber = 0x7A;

   System.out.println(hexNumber); 

This will print 122, but what if I want it to print 01111010 and 0x7A?

  • 1
    possible duplicate of [How to Print Hexadecimal Numbers in PHP or Java](http://stackoverflow.com/questions/1269573/how-to-print-hexadecimal-numbers-in-php-or-java) – Blue Ice Mar 11 '14 at 20:52
  • 1
    Note that `int hexNumber = 0x7A` and `int hexNumber = 122` does *exactly* the same thing. There's no way to tell what the base of the integer literal was once the source is compiled. – zakinster Mar 11 '14 at 20:57
  • 1
    Please understand something: there is no such thing as a "hexadecimal number" in a Java program. `int hexNumber = 0x7A` is **exactly** the same as `int hexNumber = 122` or `int hexNumber = 0b1111010`. There will be nothing in the program that "remembers" whether you used a hexadecimal, decimal, or binary integer literal to initialize it. – ajb Mar 11 '14 at 20:57
  • @zakinster I guess you win by 4 seconds... – ajb Mar 11 '14 at 20:58
  • I want to have direct access to the bits of my number, though. Be it read(user input) as hexa or decimal. –  Mar 11 '14 at 20:59
  • @user3383062 You have multiple possibilities to access each bits of an integer. Maybe you should describe what you really want to achieve. – zakinster Mar 11 '14 at 21:04
  • Found my answer. Ty for your time. –  Mar 11 '14 at 21:06
  • 1
    An `int` is not a hexidecimal, or a decimal. It is a 32-bit value. – Peter Lawrey Mar 11 '14 at 21:27

3 Answers3

5
Integer.toString(hexNumber, 16);

See

jmj
  • 237,923
  • 42
  • 401
  • 438
1

This will print 122, but what if I want it to print 01111010 and 0x7A?

Integer.toHexString(hexNumber);  // 7a
Integer.toBinaryString(hexNumber);  // 1111010
martinez314
  • 12,162
  • 5
  • 36
  • 63
0
int hexNumber = 0x7A;
System.out.println(Integer.toBinaryString(hexNumber));
System.out.println(Integer.toHexString(hexNumber));
amunozdv
  • 111
  • 3