This is just a small way to perform multiplication in Java that is close to what your computer actually does. Since computers can only understand 0 (off) and 1 (on), computer scientists had to develop smart ways to perform calculations.
Computers can only add numbers without performing tricks, so for fun I tried to program methods for multiplying, dividing, modulus and calculating square root. The results were slow to run methods. By using bitwise operators I was able to perform the calculations significantly faster.
Let's take a look at this method for performing bitwise multiplication in Java (keeping it simple not using decimal numbers):
Now examining the code we'll start at the first if statement as the while statement is self explanatory. By writing "if ((b & 1) != 0)" the computer will convert 'b' to a binary number and check the first bit if it's 0 or 1 (all odd numbers will be 1). So everyone loop where 'b' is an odd number the if statement will return true and we'll add the current number in 'a' to our result.
Next we have 2 statements outside the loop "a <<= 1;" and "b>>= 1;". These two statements convert our numbers to binary and then shift them 1 place to the left or right. Essentially this will double the number on a left shift and halve the number on a right shift. It's important to note that if a number halved gives a decimal result such as 5 / 2 = 2.5, the computer will then round that number down to 2.
A good way to see how the program works is by printing out the variables involved each loop. Let's examine the state of the variables multiplying 5 * 5:
Result: 5
Variable A: 10
Variable B: 2
---------------Next Loop------------
Result: 5
Variable A: 20
Variable B: 1
---------------Next Loop------------
Result: 25
Variable A: 40
Variable B: 0
---------------Next Loop------------
5 is added to the result the first loop because we check binary 5 (1001) for a starting 1 bit. The variable 'a' is then doubled and 'b' halved (rounded down to 2).
Next loop the result stays the same because we check binary 2 (0010) for a starting 1 bit (it fails the if statement). Once again the other variables are doubled and halved. The 3rd loop 'b' is an odd number again '0001' in binary meanining we add 'a' to result again giving us the final result.
The loop now ends since 'b' has now hit 0.
We could have just looped adding 5 every loop and decrementing 'b' until it hits 0 but this would be very ineffective and with large calculations take a long time to find the answer. The method using bitwise operators will perform almost any size calculation very quickly since we're doubling the number with every loop.
Thanks for your time and feel free to comment.
Duane

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Tuesday, 26 February 2013
Saturday, 15 December 2012
Java Simple Log Files
No matter what the program, you can be quite sure that logs are being written for whatever reason. It could be recording what a user is doing inside a website/database or recording character information in a game. In the case of a website or database it is important for companies to track potentially malicious activity, where they can see the time, person and even what action that person performed.
I wanted to do something simple where I write a username and the time the user is using the program to a text file. This example has no practical use alone but could perhaps be applied to a website/database later.
The code:
The code here probably needs a little explaining, particularly the matches statement. You should also be aware variable declarations and import statements have been excluded.
If we start from left to right, the caret "^" indicates the start of the line. The "(?i)" means we are ignoring letters case, next in the square brackets we're specifying that letters from a-z and numbers from 0-9 are valid in the String we're checking.
Just after the number check we're also allowing for underscores and hyphens. This is where the square brackets end and we're done specifying what is allowed in the String.
Finally in the curly brackets the numbers 3 and 15 are given separated by a comma. This means that the Strings length must be a minimum of 3 characters and a maximum of 15. Lastly the dollar sign indicates the end of line.
If you'd like to read more on the regular expression used, my source can be found here.
What we've just done is check for a standard format of usernames and if we find a valid username, then we exit the loop, otherwise the loop will repeat.
Moving on to writing the log:
We use try and catch because we're dealing with files and we don't want the program to crash.
You might be wondering why I use a BufferedWriter and FileWriter, this is because a BufferedWriter is more efficient at writing to files.
In my example the log file is simply being placed on the desktop. The "true" following the file path tells the program that if the file already exists, then we want to edit it and not delete the current contents.
Now the plan was to write the current date to the text file so in the following lines the date format is specified as "dd/MM/yyyy HH:mm".
You can read about what the letters mean here.
Now we got the date and we got the username, all that is left is writing to the file declared earlier in the program.
To write to the file using the BufferedWriter we call "bw.write()", where a String is given using some text and the 2 variables, after which a new line is written and we call "bw.close()" to say we're done editing the file.
The result in the file will look something like this:
Accessed by: Duane at: 15/12/2012 10:10
Thanks for your time and I hope you enjoyed it.
I wanted to do something simple where I write a username and the time the user is using the program to a text file. This example has no practical use alone but could perhaps be applied to a website/database later.
The code:
The code here probably needs a little explaining, particularly the matches statement. You should also be aware variable declarations and import statements have been excluded.
If we start from left to right, the caret "^" indicates the start of the line. The "(?i)" means we are ignoring letters case, next in the square brackets we're specifying that letters from a-z and numbers from 0-9 are valid in the String we're checking.
Just after the number check we're also allowing for underscores and hyphens. This is where the square brackets end and we're done specifying what is allowed in the String.
Finally in the curly brackets the numbers 3 and 15 are given separated by a comma. This means that the Strings length must be a minimum of 3 characters and a maximum of 15. Lastly the dollar sign indicates the end of line.
If you'd like to read more on the regular expression used, my source can be found here.
What we've just done is check for a standard format of usernames and if we find a valid username, then we exit the loop, otherwise the loop will repeat.
Moving on to writing the log:
We use try and catch because we're dealing with files and we don't want the program to crash.
You might be wondering why I use a BufferedWriter and FileWriter, this is because a BufferedWriter is more efficient at writing to files.
In my example the log file is simply being placed on the desktop. The "true" following the file path tells the program that if the file already exists, then we want to edit it and not delete the current contents.
Now the plan was to write the current date to the text file so in the following lines the date format is specified as "dd/MM/yyyy HH:mm".
You can read about what the letters mean here.
Now we got the date and we got the username, all that is left is writing to the file declared earlier in the program.
To write to the file using the BufferedWriter we call "bw.write()", where a String is given using some text and the 2 variables, after which a new line is written and we call "bw.close()" to say we're done editing the file.
The result in the file will look something like this:
Accessed by: Duane at: 15/12/2012 10:10
Thanks for your time and I hope you enjoyed it.
Sunday, 2 December 2012
Java Input Checking
If you've been programming with Java you're surely aware of the problems of taking user input, maybe you're asking for an integer and the user enters a string and the program crashes. You could write lines of code every time to stop your programs crashing and get the input you want but that needlessly bulk up on your code.
With some inspiration from Java 6 Illuminated, I wrote a class for handling user input with the Scanner class. This way you can ensure your program doesn't crash and at the same time get the correct results.
So to the code:
The method takes in a String, being the message they want to print to the console and then the loop will run until the user enters a valid integer.
Example use:
Sometimes the programmer might want to have a set range of valid values. The InputChecker class includes overloaded methods for specifying range:
Let's take an example where we ask for a persons age. We know that this will always be a positive number and is unlikely to be above 150 so we set the range from 0-150:
The example code above will loop until the user enters a number between 0-150 and then return that number.
So there you have it a class for checking input. The class works with shorts, ints, longs, floats, doubles, bytes and booleans. All you need to do is where the examples used readInt, replace Int with the data type you are using.
Download the InputChecker class below and move the file to the folder you keep your classes in:
Download
With some inspiration from Java 6 Illuminated, I wrote a class for handling user input with the Scanner class. This way you can ensure your program doesn't crash and at the same time get the correct results.
So to the code:
The method takes in a String, being the message they want to print to the console and then the loop will run until the user enters a valid integer.
Example use:
Sometimes the programmer might want to have a set range of valid values. The InputChecker class includes overloaded methods for specifying range:
Let's take an example where we ask for a persons age. We know that this will always be a positive number and is unlikely to be above 150 so we set the range from 0-150:
The example code above will loop until the user enters a number between 0-150 and then return that number.
So there you have it a class for checking input. The class works with shorts, ints, longs, floats, doubles, bytes and booleans. All you need to do is where the examples used readInt, replace Int with the data type you are using.
Download the InputChecker class below and move the file to the folder you keep your classes in:
Download
Friday, 30 November 2012
Let the Blogging Begin!
I've been studying computer science since September and during times of boredom have programmed various classes for different purposes. I got the idea to start a blog and post sections of code and classes for myself and hopefully for the benefit of others. That's where I came to Googles Blogger.
At the moment we're studying in Java but I have some experience with visual basic, C++ and a little HTML. I'll start in the next few days by posting and describing a class I wrote in Java for checking user input which has helped me in preventing errors.
Things are just starting out so there'll most likely be a lot of changes a long the way around the blogs design. For anyone reading, I bid you welcome and hope that my later posts will be of use.
Duane
At the moment we're studying in Java but I have some experience with visual basic, C++ and a little HTML. I'll start in the next few days by posting and describing a class I wrote in Java for checking user input which has helped me in preventing errors.
Things are just starting out so there'll most likely be a lot of changes a long the way around the blogs design. For anyone reading, I bid you welcome and hope that my later posts will be of use.
Duane
Subscribe to:
Posts (Atom)