1
- import java .lang .StringBuilder ;
2
- import java .util .Scanner ;
3
1
4
- class Test {
5
- private static final int sizeOfIntInHalfBytes = 8 ;
6
- private static final int numberOfBitsInAHalfByte = 4 ;
7
- private static final int halfByte = 0x0F ;
8
- private static final char [] hexDigits = {
9
- '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' ,
10
- '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F'
11
- };
2
+ class DecimalToHexaDecimal {
3
+ private static final int sizeOfIntInHalfBytes = 8 ;
4
+ private static final int numberOfBitsInAHalfByte = 4 ;
5
+ private static final int halfByte = 0x0F ;
6
+ private static final char [] hexDigits = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' ,
7
+ 'F' };
12
8
13
- public static String decToHex ( int dec ) {
14
- StringBuilder hexBuilder = new StringBuilder ( sizeOfIntInHalfBytes );
15
- hexBuilder . setLength (sizeOfIntInHalfBytes );
16
- for ( int i = sizeOfIntInHalfBytes - 1 ; i >= 0 ; -- i )
17
- {
18
- int j = dec & halfByte ;
19
- hexBuilder .setCharAt (i , hexDigits [j ]);
20
- dec >>= numberOfBitsInAHalfByte ;
21
- }
22
- return hexBuilder .toString ();
23
- }
9
+ // Returns the hex value of the dec entered in the parameter.
10
+ public static String decToHex ( int dec ) {
11
+ StringBuilder hexBuilder = new StringBuilder (sizeOfIntInHalfBytes );
12
+ hexBuilder . setLength ( sizeOfIntInHalfBytes );
13
+ for ( int i = sizeOfIntInHalfBytes - 1 ; i >= 0 ; -- i ) {
14
+ int j = dec & halfByte ;
15
+ hexBuilder .setCharAt (i , hexDigits [j ]);
16
+ dec >>= numberOfBitsInAHalfByte ;
17
+ }
18
+ return hexBuilder .toString (). toLowerCase ();
19
+ }
24
20
25
- public static void main (String [] args ) {
26
- Scanner sc = new Scanner (System .in );
27
- System .out .println ("Write your Number to convert into HexaDecimal: " )
28
- int dec = 305445566 ;
29
- String hex = Integer .toHexString (dec );
30
- String hex = decToHex (dec );
31
- System .out .println (hex );
32
- }
21
+ // Test above function.
22
+ public static void main (String [] args ) {
23
+ System .out .println ("Test..." );
24
+ int dec = 305445566 ;
25
+ String libraryDecToHex = Integer .toHexString (dec );
26
+ String decToHex = decToHex (dec );
27
+ System .out .println ("Result from the library : " + libraryDecToHex );
28
+ System .out .println ("Result decToHex method : " + decToHex );
29
+ }
33
30
}
0 commit comments