/* * Simple type conversions from string to int or double * * Created: Aug 14, 2023 * @authou gtowell */ public class Convert { public static void main(String[] args) { String baseString = "5"; int baseInt = Integer.parseInt(baseString); double baseDouble = Double.valueOf(baseString); // the point of these lines is to show the binary (0 and 1) representations // of int and double for a particular number. // // Converting a string to binary is more complex double baseDouble2 = baseInt; double baseInt2 = baseDouble; double d = 55.0; System.out.println("Double 55 => " + Long.toBinaryString(Double.doubleToRawLongBits(d))); int dd = 55; System.out.println("Int 55 => 00000000 00000000 00000000 00" + Integer.toBinaryString(dd)); String ddd = "55"; System.out.println("String 55 => " + convertStringToBinary(ddd)); } /* * This uses a lots of things that we have not taked about yet. * So ignore, for now. */ public static String convertStringToBinary(String input) { StringBuilder result = new StringBuilder(); char[] chars = input.toCharArray(); for (char aChar : chars) { result.append( String.format("%8s", Integer.toBinaryString(aChar)) // char -> int, auto-cast .replaceAll(" ", "0") // zero pads ); result.append(" "); } return result.toString(); } }