Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toHexString vs toString

 
Jerry Bustamente
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain the difference between toHexString and
toString(primitive, radix) ?

For example, the following yields the same results:

public class LongToHex {

public static void main(String[] args) {

String bob = Long.toHexString(25);
System.out.println("bob = " + bob);
String ted = Long.toString(25,16);
System.out.println("ted = " + ted);
}
}

output:

bob = 19
ted = 19

Thanks alot!

:-)

JerryB
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, there really is no difference. In fact, I wouldn't be at all surprised if the method body of toHexString really consisted nothing more than an invocation of toString. I believe toHexString is supplied as more of a convenience method than anything.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jerry,

The implementation of toHexString, toOctalString and toBinaryString is simple relative to the implementation of toString(primitive, radix), because toHexString, toOctalString and toBinaryString are working with a radix that is a power of 2. The implementation of the toString(primitive, radix) method is generalized to work with any radix including those that are not a power of 2.
 
Jerry Bustamente
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Corey and Dan.

Sincerely,

:-)

JerryB
 
kapil munjal
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Corey and Dan,

you people are really helpful, I had never seen these methods in detail but now I have been able to understand it completely.

Thanks
Kaps
 
Boris Treukhov
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A bit of necromancy(this post is showed as number one when I searched in google so I decided to post a reply).

The information above is INCORRECT,
those function differ in the way they handle negative numbers:
Long.toHexString(x) will add 2^64, so Long.toHexString(-1) will return ffffffffffffffff
Long.toString(x, 16) will use minus sign instead, so Long.toString(-1, 16) will return -1;

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic