Showing posts with label java - Integer class. Show all posts
Showing posts with label java - Integer class. Show all posts

Friday, March 9, 2018

JAVA - How convert decimal to binary, hex, octal etc.

For converting from decimal to binary, hexadecimal, octal etc., use function Integer.toString().
Second parameter is base.
String sText = "";
Integer iValue;
String sValue = "";

/* -- convert from dec */

sValue = Integer.toString( 100, 10 );
sText += "dec(100) to dec =" + sValue + "\n";

sValue = Integer.toString( 100, 2 );
sText += "dec(100) to bin =" + sValue + "\n";

sValue = Integer.toString( 100, 16 );
sText += "dec(100) to hex =" + sValue + "\n";

sValue = Integer.toString( 255, 16 );
sText += "dec(255) to hex =" + sValue + "\n";

/* result */

memo.setText( sText );      
Output:

JAVA - How convert binary, hex, octal etc. to decimal

For converting from binary, hexadecimal, octal etc. to decimal, use function Integer.parseInt(). Second parameter is base.
String sText = "";
Integer iValue;
String sValue = "";
    
/* -- convert to dec */
    
iValue = Integer.parseInt( "100", 10 );    
sText += "dec(100) to dec = " + iValue.toString() + "\n";
    
iValue = Integer.parseInt( "100", 2 );    
sText += "bin(100) to dec = " + iValue.toString() + "\n";

iValue = Integer.parseInt( "100", 16 );    
sText += "hex(100) to dec = " + iValue.toString() + "\n";

iValue = Integer.parseInt( "ff", 16 );    
sText += "hex(ff) to dec = " + iValue.toString() + "\n";

/* result */
    
memo.setText( sText );      
Output:

Wednesday, December 6, 2017

JAVA - How convent number to string

int to String

int i = 10;
String s = Integer.toString( i );

System.out.println( s );  // write result to Output window
Output:
10

long to String

long l = 456;
s = Long.toString( l );

System.out.println( s );  // write result to Output window
Output:
456

double to String

double d = 5.51;
s = Double.toString( d );

System.out.println( s );  // write result to Output window
Output:
5.51

float to String

float f = 15.55f;
s = Float.toString( f );

System.out.println( s );  // write result to Output window
The output is:
15.55