/* * [RAM.java] * * Summary: Display a number as English words used to measure RAM. * * 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 as English words used to measure RAM. *

* e.g. * 10240 -> "ten kilobytes" * * @author Roedy Green, Canadian Mind Products * @version 1.0 1999-01-17 * @since 1999-01-17 */ public final class RAM extends AmericanEnglish implements ToWords { private static final int FIRST_COPYRIGHT_YEAR = 1999; private static final String BYTE = "byte"; private static final String BYTES = "bytes"; /** * undisplayed copyright notice * * @noinspection UnusedDeclaration */ private static final String EMBEDDED_COPYRIGHT = "Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com"; private static final String MINUS = "minus"; private static final String ZERO = "zero"; private static final String[] prefixName = { /* * American: unit, ten, hundred, thousand, million, billion, trillion, * quadrillion, quintillion */ "", "kilo", "mega", "giga", "tera", "peta", "exa" }; private static final int[] divisor = { /* * HowToProcess many of this group is needed to form one of the succeeding group. */ /* American: unit, 2^10, 2^20, 2^30, 2^40, 2^50, 2^60 */ 1024, 1024, 1024, 1024, 1024, 1024, 1024 }; /** * test harness * * @param args not used */ public static void main( String[] args ) { Test.test( new RAM() ); } // end main /** * convert long integer into American English words. e.g. 10240 -> "ten kilobytes" 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 ) { if ( num == 0 ) { return ZERO + " " + BYTES; } boolean negative = ( num < 0 ); if ( negative ) { num = -num; } String s = ""; // Work least significant digit to most, right to left. // until high order part is all 0s. for ( int group = 0; num > 0; group++ ) { int remdr = ( int ) ( num % divisor[ group ] ); num = num / divisor[ group ]; if ( remdr == 0 ) { continue; } String t = super.toWords( remdr ); boolean comma = ( s.length() != 0 ); boolean plural = ( remdr != 1 ); s = t + " " + prefixName[ group ] + ( plural ? BYTES : BYTE ) + ( comma ? "," : "" ) + " " + s; } // end for s = s.trim(); if ( negative ) { s = MINUS + " " + s; } return s; } // end toWords } // end RAM