When I had nothing to do, I found a program design question to practice: Write an application and read an integer (that is, a binary integer) that only contains 0 and 1 ), then, the following decimal integer is printed. The modulo and division operators are required. So I wrote the following two methods:
Code:
- Public static long readbinarynum ()
- {
- Repeated scan = new partition (system. In );
- String binarynumstr = "";
- Boolean available = false;
- Do {
- System. Out. Print ("enter a binary INTEGER :");
- Binarynumstr = scan. nextline ();
- Available = pattern. Matches ("[0-1] +", binarynumstr );
- If (! Available)
- {
- System. Out. println ("non-binary data, this input is invalid! ");
- Continue;
- }
- If (binarynumstr. Length ()> = 19)
- {
- System. Out. println ("the data is too big. This input is invalid! ");
- Available = false;
- Continue;
- }
- } While (! Available );
- Return long. parselong (binarynumstr );
- }
- /**
- * Convert the binary value to the corresponding decimal value.
- * @ Param binarynum the binary value to be converted
- * @ Return refers to the corresponding decimal value.
- */
- Public static long binarynum2decimalnum (long binarynum)
- {
- System. Out. println (binarynum );
- Long decimalnum = 0;
- Int position [] = new int [(INT) math. log10 (binarynum) + 1];
- Position [0] = (INT) (binarynum/Math. Pow (10, position. Length-1 ));
- For (INT I = 1; I <position. length; I ++)
- {
- Position [I] = (INT) (binarynum % (math. Pow (10, position. Length-I ))
- /(Math. Pow (10, position. Length-I-1 )));
- }
- For (INT I = 0; I <position. length; I ++)
- {
- Decimalnum + = position [position. length-i-1] * Math. Pow (2, I );
- System. Out. Print (position [I] + "");
- }
- System. Out. println ();
- Return decimalnum;
- }
During the test, I found that if the input data is 11111111111111111 (that is, 17 1), the program will encounter a problem during conversion, the result is 131072 (and the correct result should be 131071), so I tested it again. The final problem is found in the remainder operation:
Code:
- Long n = 111111111111111l; // 17 1
- System. Out. println (N % math. Pow (10, 1 ));
- System. Out. println (N %10.0 );
- System. Out. println (N % 10 );
The program runs and the output result is:
Code:
- 2.0
- 2.0
- 1
When I see this, I think this should be related to the storage structure of the numeric value in the computer or the division operation mechanism, but I am not quite sure what is going on here! So I wrote this article to keep you updated. I hope you will discuss it and give me some advice!