To complete my exploration of numbers in App Inventor, I’ve written an app that converts integers between decimal and binary. It uses the standard algorithms, which I’ve just translated into blocks.
Overview of Base Conversion
For our purposes, we will be converting between strings in different bases. For example, if the user types in a string of characters representing a decimal number, the app spits out a string of characters representing a binary number. To use built-in math to do the conversion, the input string is first converted to a numeric representation, which is then manipulated to create the output string.
(For more discussion on string-to-string, string-to-numeric, and numeric-to-string conversion, see my articles Base Conversion In PHP Using Built-In Functions, Base Conversion in PHP Using BCMath, and Converting Floating-Point Numbers to Binary Strings in C.)
Here’s a screenshot listing my app’s components:
Here’s how it looks in the emulator:
I didn’t make the app commercial-grade; I just wanted to demonstrate decimal/binary conversion.
When I first wrote the blocks I made separate routines for decimal to binary conversion and binary to decimal conversion. However, for brevity, I decided to abstract them into one routine called baseConvert(), with parameters “from base” and “to base”.
The code only converts positive integers, and does not check whether the inputs are valid numerals. It can convert between numbers in any base from two to ten.
The “get fromDigit” block in the for each loop returns a character, but App Inventor converts it to a numeric value (as we want it to). In a language like C, we would do this manually by subtracting the ASCII value for ‘0’ from it. Similarly, the “get toDigit” block in the while loop returns a number, but App Inventor converts it to a character (also as we want it). In C, we would manually add the ASCII value for ‘0’ to it.
The Calls for Decimal to Binary and Binary to Decimal Conversion
Here’s the call to convert decimal to binary:
Here’s the call to convert binary to decimal:
Here is the app converting 25 to binary (11001) and then back to decimal:
Here is the app converting a large integer (1234567890123456789012) to binary (10000101110110100010010001110110000101111011000001000000011101000010
100) and then back to decimal:
(The input in the binary box is too long to display — only the ending bits are shown.)
The app can convert arbitrarily large integers, taking advantage of App Inventor’s big integer implementation. (In fact, it was in writing this conversion app that I discovered its use of big integers.)
I tested the code only in the emulator, not on a real device.
Here is the source code file, EB_d2b_b2d.aia, which you can import into App Inventor. (I did not make an “.apk” file — you can do that if you want after you import it.)