# toHexString vs toString

Jerry Bustamente

Ranch Hand

Posts: 90

posted 11 years ago

- 0

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

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

Dan Chisholm

Ranch Hand

Posts: 1865

posted 11 years ago

- 0

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.

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.

Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>

Jerry Bustamente

Ranch Hand

Posts: 90

kapil munjal

Ranch Hand

Posts: 298

Boris Treukhov

Greenhorn

Posts: 1

posted 3 years ago

- 0

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;

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;