Can someone explain this code for me? Base-Conversion Code - base-conversion

So for a homework assignment we had to make a program that converted a number from one base to another (i.e. 110 in base 2 to 6 in base 10). I asked my friend how he did his because I was having trouble and he just sent me his code and nothing else. Can someone explain the logic of this code so that I can make my own program and actually understand how to do this problem. Thanks!
import java.util.*;
public class Base_Converter {
public static final String value = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String args[]){
int x, y;
String num, base10 = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number you want to convert.");
num = scan.nextLine();
num = num.toUpperCase();
System.out.println("What base is it in?");
x = scan.nextInt();
System.out.println("What base do you want to convert it to?");
y = scan.nextInt();
if(x <= 36 && y <= 36 && x > 1 && y > 1){
base10 = toBase10(num,x);
num = newBase(base10,y);
System.out.println(num);
}
}
public static String toBase10(String num, int from){
long total = 0;
int counter = num.length();
char[] stringArray = num.toCharArray();
for(char w : stringArray){
counter--;
total += value.indexOf(w)*Math.pow(from,counter);
}
return String.valueOf(total);
}
public static String newBase(String num, int to){
String total = "";
int current = 0;
while(Integer.valueOf(num) > 0){
current = Integer.valueOf(num)%to;
total = value.charAt(current)+total;
num = String.valueOf(Integer.valueOf(num)/to);
}
return total;
}
}

I think you should be focusing not on what your friend's code does, but instead with how to do the assignment yourself, because I think your problems lie with a lack of understanding on your part. Instead of leaving you high and dry though I'll walk you through some of the specifics of base-conversion.
First, read user input. It looks like you're using Java, so just use a scanner to do this. At minimum you'll want to read the number you're converting, what base it is in, and what base the output will be in.
Next, we want to convert the number. You could directly convert numbers to each other (i.e. converting base 2 to base 8) but that requires more brainpower than I am willing to offer right now. Instead, I would suggest always first converting the user-inputted number to base 10 (much like your friend did). So how do we convert a number of an unknown base to base 10?
So let's break down how a number is represented: lets say we have the number 234 in base ten. This is equivalent to 4*10^0 + 3*10^1 + 2*10^2 or 4 + 30 + 200 = 234. You can use this same conversion for any other numbers. I.E. if the number is 1763 in base 8, the value in base 10 will be 3*8^0 + 6*8^1 + 7*8^2 + 1*8^3 or 3 + 48 + 448 + 512 = 1011 base 10(try entering 1763 here for proof. So to convert to decimal, you just need to see to multiply each individual number time your base to the power of its place minus 1. For example, since 1 is the fourth number in the 1763 you multiply it times 8^(4-1). Since, you are reading a string from the user. You'll need to convert each character of the string to an integer using the ascii chart.
Now to convert from base ten to anything. Instead of multiplying, you just divide each value and write the remainder! I'll let someone else describe this procedure.
Now just store this new value as a string doing somethings like
String output = "";
output += newValue;
In computer science, just copying someone else's code is way more harmful than helpful. Hope this helps!

Related

Trying to get my own printf function to work with variables

I am programming a display and I am able to display characters on the display by using this function:
void printChar(char *tekst, uint16_t xPos, uint16_t yPos)
{
//calculate the position the first byte should be placed on
uint16_t startPos = yPos * width_disp_byte + (xPos/8);
int i;
//put all 16 bytes on the right place on the display based on the users' input
for(i=0;i<16;i++)
{
test_image[startPos]=convertChar(*tekst,i);
startPos += width_disp_byte;
}
}
Basically I get a character and find its location in an array that I build. Than I take 16 bytes of data and put this in the display.
The next step is to display integer variables on the display. I have written a code that looks like this:
void printVariable(uint16_t integer, uint16_t xPos, uint16_t yPos)
{
uint16_t value;
uint16_t remainder;
char printValue;
//max value is 9999 that can be displayed, caused by the '4' in the for loop
for(int i = 0; i < 4;i++)
{
value = integer;
//int_power calculates the divisor. going from 3 to 0. cq 1000,100,10,1.
value /= int_power(10,(3-i));
//remove highest number from integer value (for 312, remove the 3 by substracting 300)
integer -= (value) * (int_power(10,(3-i)));
// add '0' to value to get the correct ASCII value.
value += '0';
// convert uint16_t value into char
printValue = value;
printChar(printValue,xPos,yPos);
xPos += 8;
}
}
I take a variable, lets say 3164. The first step is to divide this by 1000. The answer will be 3, since it's an integer. I display this character using the printChar function.
the next step removes 3000 from 3164 and divides the value by 100, resulting in 1. Again this value is printed using the printf function. Then 100 is removed from from 164 and then gets divided by 10 etc etc.
This code is quite limited in its use, but it fits perfectly in what I want to achieve. There is no need to print variables within a string.
The problem here is that the printChar function does not work like I have written in the code. Normally I would use the printChar function like this:
printChar("F",0,0);
This would print the character F in the topleft corner. If I want to use the printChar function like this, it doesn't work:
printChar(printValue,xPos,yPos);
The warning message says:
incompatible integer to pointer conversion passing 'char' to parameter of type 'char *'; take the address with &
If I take the address with & I don't get the correct value displayed on my display.
How can I fix this?
You only want to print ONE character, so you do not need a pointer as parameter. Your function would work like this:
void printChar(char tekst, uint16_t xPos, uint16_t yPos){
...
//depending on the Parameters of your convertChar- function either
... = convertChar(tekst,i); // if you can modify this function too
... = convertChar(&tekst,i); // if the function is to use as it is
}
The difference is in char tekst instead of char * text

How to look at a certain bit in C programming?

I'm having trouble trying to find a function to look at a certain bit. If, for example, I had a binary number of 1111 1111 1111 1011, and I wanted to just look at the most significant bit ( the bit all the way to the left, in this case 1) what function could I use to just look at that bit?
The program is to test if a binary number is positive or negative. I started off by using hex number 0x0005, and then using a two's compliment function to make it negative. But now, I need a way to check if the first bit is 1 or 0 and to return a value out of that. The integer n would be equal to 1 or 0 depending on if it is negative or positive. My code is as follows:
#include <msp430.h>
signed long x=0x0005;
int y,i,n;
void main(void)
{
y=~x;
i=y+1;
}
There are two main ways I have done something like this in the past. The first is a bit mask which you would use if you always are checking the exact same bit(s). For example:
#define MASK 0x80000000
// Return value of "0" means the bit wasn't set, "1" means the bit was.
// You can check as many bits as you want with this call.
int ApplyMask(int number) {
return number & MASK;
}
Second is a bit shift, then a mask (for getting an arbitrary bit):
int CheckBit(int number, int bitIndex) {
return number & (1 << bitIndex);
}
One or the other of these should do what you are looking for. Best of luck!
bool isSetBit (signed long number, int bit)
{
assert ((bit >= 0) && (bit < (sizeof (signed long) * 8)));
return (number & (((signed long) 1) << bit)) != 0;
}
To check the sign bit:
if (isSetBit (y, sizeof (y) * 8 - 1))
...

Reduce number of decimals

In AS3, from a division I get a number like this one: 0.9130406010219044.
Is there any way to reduce the number of decimals (aside from multiplying that number for one million)? Is there a way to reduce the numbers BEFORE the division is performed?
Got the following function from this link, which rounds to an arbitrary number of decimals:
public function trim(theNumber:Number, decPlaces:Number) : Number {
if (decPlaces >= 0) {
var temp:Number = Math.pow(10, decPlaces);
return Math.round(theNumber * temp) / temp;
}
return theNumber;
}
// Round a number to two decimal places trace(trim(1.12645, 2));
// Displays: 1.13
Note: I slightly changed the function definition by adding types. See the link for explanation and original source code. Also made it return theNumber if decPlaces is less than or equal to zero.
var myNumber:Number = 74.559832;
trace(myNumber.toFixed(4)); //74.5598
trace(myNumber.toFixed(2)); //74.56
AS3 Documentation: Number class
If you just want to display the result (you didn't specify) then a simple bit of String manipulation will yield the fastest result:
0.9130406010219044.toString().substr(0, 4); // 0.91
Take a look at NumberFormatter.fractionalDigits
Or, if you're working in Flex: mx:NumberFormatter.precision / s:NumberFormatter.fractionalDigits
Try some of the answers here on for size:
How to deal with Number precision in Actionscript?
If you use a NumberFormatter, make sure to specify rounding (it's most likely you'll want nearest).
If you need Number as result and performance, I would say this solution is more efficient than the Math.pow()
If you need 3 decimals just change 100 by 1000.
var myNumber:Number = 3.553366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.55
demonstrating the rounding :
var myNumber:Number = 3.557366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.56
Regarding the Number.toFixed() returning a String I guess it's because it returns 2 decimals in any case:
For instance :
Number(3).toFixed(2); // trace 3.00 so it has to be a String.

Howto convert decimal (xx.xx) to binary

This isn't necessarily a programming question but i'm sure you folks know how to do it. How would i convert floating point numbers into binary.
The number i am looking at is 27.625.
27 would be 11011, but what do i do with the .625?
On paper, a good algorithm to convert the fractional part of a decimal number is the "repeated multiplication by 2" algorithm (see details at http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/, under the heading "dec2bin_f()"). For example, 0.8125 converts to binary as follows:
1. 0.8125 * 2 = 1.625
2. 0.625 * 2 = 1.25
3. 0.25 * 2 = 0.5
4. 0.5 * 2 = 1.0
The integer parts are stripped off and saved at each step, forming the binary result: 0.1101.
If you want a tool to do these kinds of conversions automatically, see my decimal/binary converter.
Assuming you are not thinking about inside a PC, just thinking about binary vs decimal as physically represented on a piece of paper:
You know .1 in binary should be .5 in decimal, so the .1's place is worth .5 (1/2)
the .01 is worth .25 (1/4) (half of the previous one)
the .001 is worth (1/8) (Half of 1/4)
Notice how the denominator is progressing just like the whole numbers to the left of the decimal do--standard ^2 pattern? The next should be 1/16...
So you start with your .625, is it higher than .5? Yes, so set the first bit and subtract the .5
.1 binary with a decimal remainder of .125
Now you have the next spot, it's worth .25dec, is that less than your current remainder of .125? No, so you don't have enough decimal "Money" to buy that second spot, it has to be a 0
.10 binary, still .125 remainder.
Now go to the third position, etc. (Hint: I don't think there will be too much etc.)
There are several different ways to encode a non-integral number in binary. By far the most common type are floating point representations, especially the one codified in IEEE 754.
the code works for me is as below , you can use this code to convert any type of dobule values:
private static String doubleToBinaryString( double n ) {
String val = Integer.toBinaryString((int)n)+"."; // Setting up string for result
String newN ="0" + (""+n).substring((""+n).indexOf("."));
n = Double.parseDouble(newN);
while ( n > 0 ) { // While the fraction is greater than zero (not equal or less than zero)
double r = n * 2; // Multiply current fraction (n) by 2
if( r >= 1 ) { // If the ones-place digit >= 1
val += "1"; // Concat a "1" to the end of the result string (val)
n = r - 1; // Remove the 1 from the current fraction (n)
}else{ // If the ones-place digit == 0
val += "0"; // Concat a "0" to the end of the result string (val)
n = r; // Set the current fraction (n) to the new fraction
}
}
return val; // return the string result with all appended binary values
}

Generating combination of letters

Given a set of letters, say from A.. F, how can one generate a combination of these letters for a specific length. i.e for length 4, generate all string containing these letters {AAAA, ABCD, ...} (duplicates included). I am not able to understand how to come out with a code that does it.This is pertaining to the Mastermind game that I am trying to simulate. Is there any algorithm to perform this generation.
regards,
darkie
There is an algorithm called Heap's Algorithm for generating permutations. This might suit your purposes. I found an example implementation here
I'm not sure what the name would be of such an algorithm, but it is a recursive one. That is, have a method that figures out one character, and simply keep calling itself until you're at the desired length of string that you want, then start filling in your array. Here's some sample C# code that should help:
public void GetPermutations()
{
string currentPrefix = ""; // Just a starting point
int currentLength = 1; // one-based
int desiredLength = 4; // one-based
string alphabet = "ABCDEF"; // Characters to build permutations from
List<string> permutations = new List<string>();
FillPermutations(currentPrefix, currentLength, alphabet, desiredLength, permutations);
}
public void FillPermutations(string currentPrefix, int currentLength, string alphabet, int desiredLength, List<string> permutations)
{
// If we're not at the desired depth yet, keep calling this function recursively
// until we attain what we want.
for (int i = 0; i < alphabet.Length; i++)
{
string currentPermutation = currentPrefix + alphabet[i].ToString();
if (currentLength < desiredLength)
{
// Increase current length by one and recurse. Current permutation becomes new prefix
int newCurrentLength = currentLength + 1;
FillPermutations(currentPermutation, newCurrentLength, alphabet, desiredLength, permutations);
}
else
{
// We're at the desired length, so add this permutation to the list
permutations.Add(currentPermutation);
}
}
}