/* * [Binary.java] * * Summary: display a number in binary. * * 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 binary. *

* e.g. * -12345 -> 11111111_11111111_11111111_11111111_11111111_11111111_11001111_11000111 * * @author Roedy Green, Canadian Mind Products * @version 1.0 1999-01-17 * @since 1999-01-17 */ public final class Binary 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 Binary() ); } // end main /** * convert long integer into Binary e.g. -12345 -> * 11111111_11111111_11111111_11111111_11111111_11111111_11001111_11000111 * 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 & 0x7fffffffffffffffL, 2 ); // pad out to 63 bits h = "000000000000000000000000000000000000000000000000000000000000000" .substring( h.length() ) + h; h = Integer.toString( ( int ) ( num >>> 63 ), 2 ) + h; } else { h = Long.toString( num, 2 ); // pad out to 64 bits h = "0000000000000000000000000000000000000000000000000000000000000000" .substring( h.length() ) + h; } // insert decorative underscores every 8 chars to help make it easier to // read. return h.substring( 0, 8 ) + '_' + h.substring( 8, 16 ) + '_' + h.substring( 16, 24 ) + '_' + h.substring( 24, 32 ) + '_' + h.substring( 32, 40 ) + '_' + h.substring( 40, 48 ) + '_' + h.substring( 48, 56 ) + '_' + h.substring( 56 ); } // end inWords } // end Binary