bitwise operation to extract each individual word from a long - java

I have a long that corresponds to an assembly language instruction.
Here's the problem; the first field is Opcode. It can be either 1 or 2 digits. So for example in 120602, 12 is the opcode. In 10602, 1 is the opcode.
I want to extract each individual field; where opcode is the first 1-2 numbers on the left, 1 to the right of that is op1mode, 1 to the right of that is op1gpr, 1 to the right of that is op2mode, and finally, the last part is op2gpr.
Ideally, I want to assign each to its own variable for later use, or separate them in an array.
I was thinking that this can be achievable using bitwise operations; namely masks and shifts.
How would one split the number with just bitwise operations?

Bitwise/bitshifts won't do you any good unless the fields are combined in a base 2 representation. As shown, your digits are base 10. On the other hand, you can use integer division and modulo for the numbers you've shown.
120602 / 10000 = 12
120602 % 10000 = 602
These basically correspond to the following types of operations for binary digits:
0x1D71A >>> 12 = 0x1D
0x1D71A & 0xFFF = 0x71A

An easy way to do that (but without bit manipulation), is to define an array containing five integers, and then to fill it which the digits of your number. You will have to begin from the end of the number, it is easier.
An example in Java:
long number = 120602;
int[] op = new int[5];
for(int i = 0; i < 4; ++i) {
op[i] = (int) (number % 10);
number /= 10;
}
op[4] = (int) number;
And here:
op[0] is op2gpr
op[1] is op2mode
op[2] is op1gpr
op[3] is op1mode
op[4] is opcode

Related

How can I add a placeholder to a random Int then pull a single digit from that Int in Java?

I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.

how to convert negative number to binary in java?

I'm trying to convert a negative long number (e.g. -1065576264718330231L) to binary.
First, I convert negative number to positive one by removing the sign;
Second, I get the binary of the result from first step;
then I get stuck with "add one" to the binary result of the second step,that is :
please! how to implement the third step?
or do you have other better solutions?!
http://geekexplains.blogspot.com/2009/05/binary-rep-of-negative-numbers-in-java.html
Signed integers/longs use the two-complements notation:
Say you have -6:
6 = 000..000 110 binary
111..111 001 one's complement
111..111 010 add 1
-6 = 111..111 010
The advantage is that normal binary addition works (-6+6=0), there is just one 0.
Of you could simply subtract 6 from 0:
000
110
------ -
0
1 borrow 1 (all ones at the top)
0
...111
111...111010 = -6
Note:
If one borrows (subtracts one of) 0000000, one actually uses an overflow:
(1)0000000 which minus 1 delivers
1111111
Goodies:
long n = -1065576264718330231L;
System.out.println(Long.toUnsignedString(n, 2));
System.out.println(Long.toString(n, 2));
Given the long value is -1065576264718330231L.
long v = -1065576264718330231L;
System.out.println(Long.toBinaryString(v));
Or you can code the algorithm yourself
StringBuilder sb = new StringBuilder();
while (v != 0) {
sb.append(v < 0 ? '1'
: '0');
v <<= 1;
}
System.out.println(sb.toString());
If you want to convert a positive number to negative using 2's complement you can do the following:
long pos = 23;
long neg = ~pos + 1;
System.out.println(pos);
System.out.println(neg);
But all Strings, ints, longs, etc. are inherently stored in binary and are displayed in different formats based on context.

How to convert large integer number to binary?

Sorry for a possible duplicate post, I saw many similar topics here but none was exactly I needed. Before actually posting a question I want to explicitly state that this question is NOT A HOMEWORK.
So the question is: how to convert a large integer number into binary representation? The integer number is large enough to fit in primitive type (Java long cannot be used). An input might be represented as a string format or as an array of digits. Disclaimer, This is not going to be a solution of production level, so I don't want to use BigInteger class. Instead, I want to implement an algorithm.
So far I ended up with the following approach:
Input and output values represented as strings. If the last digit of input is even, I prepend the output with "0", otherwise - with "1". After that, I replace input with input divided by 2. I use another method - divideByTwo for an arithmetical division. This process runs in a loop until input becomes "0" or "1". Finally, I prepend input to the output. Here's the code:
Helper Method
/**
* #param s input integer value in string representation
* #return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
Main Method
/**
* #param s the integer in string representation
* #return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
As you can see, the runtime is O(n^2). O(n) for integerToBinary method and O(n) for divideByTwo that runs inside the loop. Is there a way to achieve a better runtime? Thanks in advance!
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
Among the simple methods there are two possible approaches (all numbers that appear here decimal)
work in decimal and divide by 2 in each step as you outlined in the question
work in binary and multiply by 10 in each step for example 123 = ((1 * 10) + 2) * 10 + 3
If you are working on a binary computer the approach 2 may be easier.
See for example this post for a more in-depth discussion of the topic.
In wikipedia, it is said:
For very large numbers, these simple methods are inefficient because
they perform a large number of multiplications or divisions where one
operand is very large. A simple divide-and-conquer algorithm is more
effective asymptotically: given a binary number, it is divided by
10^k, where k is chosen so that the quotient roughly equals the
remainder; then each of these pieces is converted to decimal and the
two are concatenated. Given a decimal number, it can be split into two
pieces of about the same size, each of which is converted to binary,
whereupon the first converted piece is multiplied by 10^k and added to
the second converted piece, where k is the number of decimal digits in
the second, least-significant piece before conversion.
I have tried, this method is faster than conventional one for numbers larger than 10,000 digits.

truncated binary logarithm

I have a question about this problem, and any help would be great!
Write a program that takes one integer N as an
argument and prints out its truncated binary logarithm [log2 N]. Hint: [log2 N] = l is the largest integer ` such that
2^l <= N.
I got this much down:
int N = Integer.parseInt(args[0]);
double l = Math.log(N) / Math.log(2);
double a = Math.pow(2, l);
But I can't figure out how to truncate l while keeping 2^l <= N
Thanks
This is what i have now:
int N = Integer.parseInt(args[0]);
int i = 0; // loop control counter
int v = 1; // current power of two
while (Math.pow(2 , i) <= N) {
i = i + 1;
v = 2 * v;
}
System.out.println(Integer.highestOneBit(N));
This prints out the integer that is equal to 2^i which would be less than N. My test still comes out false and i think that is because the question is asking to print the i that is the largest rather than the N. So when i do
Integer.highestOneBit(i)
the correct i does not print out. For example if i do: N = 38 then the highest i should be 5, but instead it prints out 4.
Then i tried this:
int N = Integer.parseInt(args[0]);
int i; // loop control counter
for (i= 0; Math.pow(2 , i) == N; i++) {
}
System.out.println(Integer.highestOneBit(i));
Where if i make N = 2 i should print out to be 1, but instead it is printing out 0.
I've tried a bunch of things on top of that, but cant get what i am doing wrong. Help would be greatly appreciated. Thanks
I believe the answer you're looking for here is based on the underlying notion of how a number is actually stored in a computer, and how that can be used to your advantage in a problem such as this.
Numbers in a computer are stored in binary - a series of ones and zeros where each column represents a power of 2:
(Above image from http://www.mathincomputers.com/binary.html - see for more info on binary)
The zeroth power of 2 is over on the right. So, 01001, for example, represents the decimal value 2^0 + 2^3; 9.
This storage format, interestingly, gives us some additional information about the number. We can see that 2^3 is the highest power of 2 that 9 is made up of. Let's imagine it's the only power of two it contains, by chopping off all the other 1's except the highest. This is a truncation, and results in this:
01000
You'll now notice this value represents 8, or 2^3. Taking it down to basics, lets now look at what log base 2 really represents. It's the number that you raise 2 to the power of to get the thing your finding the log of. log2(8) is 3. Can you see the pattern emerging here?
The position of the highest bit can be used as an approximation to it's log base 2 value.
2^3 is the 3rd bit over in our example, so a truncated approximation to log base 2(9) is 3.
So the truncated binary logarithm of 9 is 3. 2^3 is less than 9; This is where the less than comes from, and the algorithm to find it's value simply involves finding the position of the highest bit that makes up the number.
Some more examples:
12 = 1100. Position of the highest bit = 3 (starting from zero on the right). Therefore the truncated binary logarithm of 12 = 3. 2^3 is <= 12.
38 = 100110. Position of the highest bit = 5. Therefore the truncated binary logarithm of 38 = 5. 2^5 is <= 38.
This level of pushing bits around is known as bitwise operations in Java.
Integer.highestOneBit(n) returns essentially the truncated value. So if n was 9 (1001), highestOneBit(9) returns 8 (1000), which may be of use.
A simple way of finding the position of that highest bit of a number involves doing a bitshift until the value is zero. Something a little like this:
// Input number - 1001:
int n=9;
int position=0;
// Cache the input number - the loop destroys it.
int originalN=n;
while( n!=0 ){
position++; // Also position = position + 1;
n = n>>1; // Shift the bits over one spot (Overwriting n).
// 1001 becomes 0100, then 0010, then 0001, then 0000 on each iteration.
// Hopefully you can then see that n is zero when we've
// pushed all the bits off.
}
// Position is now the point at which n became zero.
// In your case, this is also the value of your truncated binary log.
System.out.println("Binary log of "+originalN+" is "+position);

What would be the most performant (also safe) way to replace the last digit of a long?

What would be the most performant (also safe) way to replace the last digit(Least significant digit) of a long(that was actually generated as timestamp by System.currentTimeInMillis()) by some other digit?
Or is there a better way to attach any fixed attachment to the end of it, by making use of bitwise operations?
In your comments you say that both binary digits or decimal digits would be fine. Since Andrew posted the decimal version, i post the binary version in which you want to replace the 2 ls-bits:
The following program goes through the 4 possibilities with which you can replace the 2 ls-bits and produces the output:
9999999999999999
9999999999999996
9999999999999997
9999999999999998
9999999999999999
code:
public class A {
public static void main(String[] args) {
long aLong = 9999999999999999L;
System.out.println(aLong);
long aLong2 = aLong & ~3 + 0;
System.out.println(aLong2);
aLong2 = aLong & ~3 + 1;
System.out.println(aLong2);
aLong2 = aLong & ~3 + 2;
System.out.println(aLong2);
aLong2 = aLong & ~3 + 3;
System.out.println(aLong2);
}
}
If this is not a hypothetical question, ie to find a fast algorithm for the heck of it, then please ignore this answer. The correct way (as has been mentioned) is to do (somelong/10)*10 + newvalue
A faster (hypothetical) way is probably to have some two dimension array of adjustment values.
int[][] adjustment = new int[16][10];
where the first array index represents what the current value is anded with 0x0F (the last 4 bits)
the second array index would be what you want the new number to be
the value is the adjustment to the variable
so the code would be
newLong = somelong + adjustment[somelong&0x0F][what_you_want_the_new_digit];
so no multiplication or division
as an example, let's say the input number is 22, and you want it to be 26
26 is 011010 so 26 & 0x0F is the bottom 4 bits 1010 which is 10
adjustment[10][6] = 4 (you have precalculated that it is 4)
so you'd have 22 + 4 = 26
obviously index 10 is the same as index 0, index 11, is the same as index 1, etc, etc.

Categories

Resources