/* * [Hex.java] * * Summary: Display a number in hexadecimal (base16). * * Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 1999-01-17 */ package com.mindprod.inwords; /** * Display a number in hexadecimal (base16). *

* e.g. * -12345 -> ffff_ffff_ffff_cfc7 *

* Products * * @author Roedy Green, Canadian Mind Products * @version 1.0 1999-01-17 * @since 1999-01-17 */ public final class Hex implements ToWords { private static final int FIRST_COPYRIGHT_YEAR = 1999; /** * undisplayed copyright notice * * @noinspection UnusedDeclaration */ private static final String EMBEDDED_COPYRIGHT = "Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com"; /** * test harness * * @param args not used */ public static void main( String[] args ) { Test.test( new Hex() ); } // end main /** * convert long integer into Hexadecimal e.g. -12345 -> ffff_ffff_ffff_cfc7 Handles negative and positive integers * on range -Long.MAX_VALUE .. Long.MAX_VALUE; It cannot handle Long.MIN_VALUE; * * @param num number to convert to words * * @return words */ @SuppressWarnings( { "WeakerAccess" } ) public String toWords( long num ) { String h; if ( num < 0 ) { h = Long.toString( num & 0x0fffffffffffffffL, 16 ); // pad out to 15 digits h = "000000000000000".substring( h.length() ) + h; // tack on high order digit h = Integer.toString( ( int ) ( num >>> 60 ), 16 ) + h; } else { h = Long.toString( num, 16 ); // pad out to 16 digits h = "0000000000000000".substring( h.length() ) + h; } // insert decorative _ ever 4 chars to make it easier to read return h.substring( 0, 4 ) + '_' + h.substring( 4, 8 ) + '_' + h.substring( 8, 12 ) + '_' + h.substring( 12 ); } // end toWords } // end Hex