Location>code7788 >text

Basic Computer Principles: Decimal and Binary Interchange Logic

Popularity:209 ℃/2024-07-23 12:33:29
package ; import ; import ; /** * @Auther: yuzj * @Date: 2024/7/23 - 07 - 23 - 7:39 * @Description: * @version: 1.0 */ public class BinaryConversion { private static final ArrayList<Long> bitMapDecimalPom = new ArrayList<Long>(); static { for (int i = 32-1; i >= 0; i--) { (new Double((2,i)).longValue()); } } private static char[] bitStringToChar(String bit32string) throws Exception { char[] bit32charArray = (); if (() > 32) { throw new Exception("The bit32string parameter passed in by the bitStringToChar function is longer than 32 bits")); } for (char c : bit32charArray){ if (c != '0' && c != '1') { throw new Exception("bit32charArray parameter content has data other than 0 and 1")); } } return bit32charArray; } // The main function of the bitToDecimal method is to convert from binary to decimal. private static Long bitToDecimal(String bit32string) throws Exception { Long DecimalNum = 0l; // Incoming binary strings are converted to char arrays. char[] bit32Chars = bitStringToChar(bit32string); // bit32CharsLength is the length of the bit32Chars array. int bit32CharsLength = ; for (int i = () -1 ; i >= 0; i--) { if (bit32Chars[bit32CharsLength-1] == '1'){ DecimalNum = DecimalNum + (i); } // bit32Chars offset from right to left bit32CharsLength = bit32CharsLength - 1; // bit32Chars offset from right to left, index to 0 to end loop if (bit32CharsLength == 0){ break; } } return DecimalNum; } // DecimalToBit: Convert decimal to binary. private static String DecimalToBit(Integer Decimal32int) throws Exception { // First define an array ArrayList<String> DecimalArr = new ArrayList<String>(); //Here's the logic. If 123 is passed in, it's assigned to DecimalModNum. Integer DecimalModNum = Decimal32int; Integer modNum = null; if (Decimal32int > Integer.MAX_VALUE ){ throw new Exception("DecimalToBit method passed bit32int parameter greater than 2147483648")); } // If DecimalModNum is not equal to 0, the loop continues. while (DecimalModNum != 0){ // If DecimalModNum is 123, then 123 to 2, take the remainder of 1 and put it into modNum, then throw the remainder into DecimalArr. modNum = DecimalModNum % 2 ; (()); // Then 123➗2 equals 61 integer result, and continue to take the result and ÷2, dividing until 0. DecimalModNum = DecimalModNum /2 ; } // Flip the value of the remainder (DecimalArr); StringBuilder stringBuilder = new StringBuilder(); for (String s :DecimalArr){ (s); } return (); } public static void main(String[] args) throws Exception { // Conversion from decimal to binary String bitNum = DecimalToBit(999); ("999 converted to binary:" + bitNum); (""); // Convert binary to decimal Long DecimalNum = bitToDecimal(bitNum); ("1111100111 converted to decimal:" + DecimalNum); } }