Decimal to Binary Format Conversion - java

I have to write a Java program as part of an assignment to convert decimal inputs to the following formats: unsigned binary, unsigned hex, signed-magnitude, 1’s complement and 2’s complement. The issue is that I am not allowed to use any of the built-in java components that would otherwise not make this so difficult. I've been working on this for a number of hours, and the last thing I wanted to do was come on here and ask for help, but I really am stumped here. I do not expect, nor am I looking for anyone to complete my homework for me. All I ask is for a nudge in the right direction.
The output/input of the program must be as follows:
Enter num bytes: 2
Enter number (or Q to quit): 4095
Input number=4095
Unsigned binary = 0000 1111 1111 1111 (0x0fff)
Signed-magnitude = 0000 1111 1111 1111
One's complement = 0000 1111 1111 1111
Two's complement = 0000 1111 1111 1111
Excess 32768 = 1000 1111 1111 1111
Enter number (or Q to quit): -4095
Input number=-4095
Unsigned binary = undefined
Signed-magnitude = 1000 1111 1111 1111
One's complement = 1111 0000 0000 0000
Two's complement = 1111 0000 0000 0001
Excess 32768 = 0111 0000 0000 0001
I have a good understanding of how to calculate these values, and I have worked out many of the algorithms accordingly. The issue I'm having is that I don't know how to properly organize my classes to make this program efficient. Mostly, I'm getting confused by the instructions I've been given.
They read as follows:
Don’t use the byte data type in Java. We want to show the algorithms we use to do binary encodings. I created a simplistic BitString class. It’s one field is an array of char’s. It has methods like: BitString( numBytes), clear(), invert(), encodeUnsigned( num), setBit( pos, char).
I don't understand why we would want to use a char array to store these bit values. I've set this up so that the constructor in BitString accepts an argument for the number of bytes, multiplies that by 8 and creates a new char array using this number. Then to obtain the unsigned binary value of the decimal, I've implemented the following:
String unsigned = "";
while(decimal > 0)
{
unsigned = decimal%2 + unsigned;
decimal = decimal >> 1;
}
I don't know what I'm supposed to do from here to be able to store these values in that array so that I can use it to calculate the other formats. I can't seem to be able to store integers as chars and I'm confused on how I am supposed to use that data structure to perform the other operations. To complicate matters further, you'll notice that I need to pad the data so that it contains the correct number of bits.
If this were your problem, how would you solve it and how would you lay it out? I'm looking for the most fundamental solution that would be easy for a novice like me to understand.
Thank you very much.

The instructions probably mean that, instead of
String unsigned = "";
The data would be more easily manipulated into other formats with something like (this is pseudo-code, I don't really know java):
char unsigned[numBytes * 8];
The array stores one bit per location.
To do bitwise operations, you just iterate through the array and operate on each "bit."

Related

Java - How to Extract Certain Portions of Bits Using Bit Mask?

This is the first time I am looking at bitwise operations and bit mask. I have seen some examples using C and C++, but I am looking for clarification using Java.
I have the following 32-bit string
0000 0000 1010 0110 0011 1000 0010 0000
But I want to extract bits 21 through 25 in bold (00101) and ignore everything else. In the end, I want my output result to be integer 5 (0101 in binary)
Using bit mask, what approach I could use to get just that bit portion as my output result?
If you really have a String, take the two substrings (00 and 101), concatenate them, and use Integer.parseInt with a radix of two:
int bits = Integer.parseInt(str.substring(7, 9) + str.substring(10, 13), 2);
If you have an int, use a logical right shift, then use & with a bit mask (0b signifies binary notation).
int bits = (n >>> 21) & 0b11111;

Two Ways to Interpret Integer Overflow

I have read here (https://stackoverflow.com/a/27762490/4415632) that when integer overflow occurs, the most significant bits are simply cut off.
However, I have also read here (https://stackoverflow.com/a/27747180/3808877) that when overflow occurs, "the value becomes the minimum value of the type, and start counting up again." Which one is correct, or are both answers correct? If so, can anyone show me why those two interpretations are equivalent to each other?
Both are correct, it depends on context. One is the result of casting and one is the result of overflow. Those are different operations. For example, if you cast Long.MAX_VALUE to an int that is a cast operation
System.out.println((int) Long.MAX_VALUE); // <-- -1
If you overflow an int by adding one to Integer.MAX_VALUE then
System.out.println(Integer.MAX_VALUE + 1); // <-- Integer.MIN_VALUE
Both interpretations are correct, because they are actually the same.
Let's look at the maths to see why.
Java stores values in byte, short, char, int and long in a format called two's complement.
In case of byte, short, int and long it is signed, in case of char it is unsigned.
One of the attributes of the two's complement format is that for most operations it does not matter whether the value is interpreted as signed or unsigned as the resulting bit pattern would be the same.
To shorten things, I'll explain it using byte, but the other types work along the same scheme.
A byte has 8 bits. The topmost bit is interpreted as sign bit. So, the bit pattern goes like this:
snnn nnnn
The separation into two groups of 4 bits each is called Nibble and is performed here for pure readability. As a side note, a nibble can be represented by a hexadecimal digit.
So there are 8 bits in a byte, and each bits could be 0 or 1. This leaves us with 2^8 = 256 different values that could be stored in a byte.
Here are some sample values:
0000 0000 -> 0
0000 0001 -> 1
0000 0010 -> 2
0100 0000 -> 64
0111 1111 -> 127
1000 0000 -> -128
1111 1110 -> -2
1111 1111 -> -1
The 2's complement value of signed numbers which are negative, i.e. the sign bit is set, is created by taking the positive value of the 8 bits and subtracting the range, i.e. in case of a byte by subtracting 256.
Now let's see what happens if you take -1 and add 1.
1111 1111 -1 / 255
+ 0000 0001 1
--------------
= 1 0000 0000 -0 / 256 intermediate result
= 0000 0000 0 / 256 result after dropping excess leading bits
There is an overflow. The result would need 9 bits now, but the byte only has 8 bits, so the most significant bit is lost.
Let's look at another example, -1 plus -1.
1111 1111 -1 / 255
+ 1111 1111 -1 / 255
--------------
= 1 1111 1110 -2 / 510 intermediate result
= 1111 1110 -2 / 254 result after dropping excess leading bits
Or this, 127 plus 5.
0111 1111 127
+ 0000 0101 5
--------------
= 1000 0100 132 / -124
As we can see, the leading bits are dropped and this actually is what leads to the effect that causes it to overflow by "starting to count from the minimum value again".
I add another option: a processor trap. Some processors will generate a trap on integer overflows. When available, this feature usually can be enabled in user mode by setting a bit in the processor status register.

Binary presentation of negative integer in Java

Please, help me to understand binary presentation of negative integers.
For example we have 5.
Binary presentation of 5 is 00000000.00000000.00000000.00000101.
And as I understand binary presentation of -5 should be like 10000000.00000000.00000000.00000101.
But output is 11111111.11111111.11111111.11111011.
I have 2 question:
1) Why here is so much 1 bits.
2) What I really cant understand it last 3 bits 011. It looks like 3. Even +1 or -1 it'll be 100 or 010
Thanks
Your understanding of what those negative numbers should look like is flawed. Java uses two's complement for negative numbers and the basic rule is to take the positive, invert all bits then add one. That gets you the negative.
Hence five is, as you state:
0000...00000101
Inverting that gives you:
1111...11111010
Then adding one gives:
1111...11111011
The bit pattern you have shown for -5 is what's called sign/magnitude, where you negate a number simply by flipping the leftmost bit. That's allowed in C implementations as one of the three possibilities(a), but Java uses two's complement only (for its negative integers).
(a) But keep in mind there are current efforts in both C and C++ to remove the other two encoding types and allow only two's complement.
And as I understand binary presentation of -5 should be like 10000000.00000000.00000000.00000101.
That would be right if Java used a Sign and Magnitude representation for integers. However, Java uses Two's Complement representation, so the rest of the bits are changed in accordance with the rules of that representation.
The idea behind two's complement representation is that when you add a number in such representation to another value dropping the extra bit on the most significant end, the result would be as if you subtracted a positive number of the same magnitude.
You can illustrate this with decimal numbers. In a two-digit representation, the value of 99 would behave like -1, 98 would be like -2, 97 like -3, and so on. For example, if you drop the top digit in 23 + 99 = [1]22, so 99 behaved like -1. 23 + 98 = [1]21, so 98 behaved like -2.
This works the same way with two's complement representation of binary numbers, except you would drop the extra bit at the top.
http://en.wikipedia.org/wiki/Two%27s_complement
The way negative numbers are stored is that the most significant bit (e.g. the bit representing 2^31 for a 32 bit number) is regarded as negative. So if you stored all 1s, you would add up
(-2^31) + 2^30 + 2^29 + ... + 2^1 + 2^0
which makes -1.
Small negative numbers will be mostly ones under this representation.
Here is an example for 2's compliment:
If you have -30, and want to represent it in 2's complement, you take the binary representation of 30:
0000 0000 0000 0000 0000 0000 0001 1110
Invert the digits.
1111 1111 1111 1111 1111 1111 1110 0001
And add one.
1111 1111 1111 1111 1111 1111 1110 0010
Converted back into hex, this is 0xFFFFFFE2. And indeed, suppose you have this code:
#include <stdio.h>
int main() {
int myInt;
myInt = 0xFFFFFFE2;
printf("%d\n",myInt);
return 0;
}
That should yield an output of -30. Try it out if you like.
With two's complement it's true that a MSB of 1 indicates a negative number. But the remaining bits are not the binary representation of its value. On the other hand, if the MSB is 0 the remaining bits represent the binary value. But it cannot be said that the number is positive then. Zero is neither positive nor negative.
This picture helped me to understand the principle when I started to learn that there are more representations of numbers than with 0..9:
0
-1 000 1
111 001
-2 110 010 2
101 011
-3 100 3
-4

Calculate Java Int Overflow

Is there a formula to calculate what the overflow of a Java int would be?
Example: if I add 1 to Integer.MAX_VALUE; the answer is not 2147483648, but rather -2147483648.
Question: if I wanted to calculate what Java would print for a value larger than 2^32, is there an easy mathematical expression (theoretical, not in code)?
((x + 231) mod 232) - 231
Is this what you're looking for? That should be the result of any mathematical operation on a machine that uses 32-bit signed 2's complement integers. That is, if the mathematical value of an operation returns x, the above formula gives the integer that would actually be stored (if the operation doesn't fault, and it's not a "saturating" operation).
Note that I'm using "mod" with a mathematical definition, not the way the % operator works in Java or C. That is, A mod B, where A and B are integers and B > 0, always returns an integer in the range 0 .. B-1, e.g. (-1) mod 5 = 4. More specifically, A mod B = A - B*floor(A/B).
In java an int is 32 bits but it is also signed, which means that the first bit is the "negative" sign. 1 means negative and 0 means positive. Because of this, the largest number is 2147483647 (0111 1111 1111 1111 1111 1111 1111 1111). If you add 1 it makes it 1000 0000 0000 0000 0000 0000 0000 0000 which translates to -2147483648. For any values larger than that you would need to use a long
I believe this would work:
int expected = ((val + Integer.MAX_VALUE) % Integer.MAX_VALUE) - Integer.MAX_VALUE;

What is the meaning of 0x1234ABCD when working with raw bytes

When dealing with byte operations in Java, I saw sometimes that people masked a 0xFFFFFFFF long value (32bit value) with 0x1234ABCD
I know that Java does not support unsigned integer values (except char) but I would like to understand the meaning (if any) of these numbers 0x1234ABCD and 0xABCD1234 and also what is the significance to use them when working with raw bytes in Java?
Not sure what you are asking but anyway...
With Java, integer values (whether that be byte, short, char, int or long) are expressed as big endian, two's complement signed values. What you see here is another way than the decimal way of expressing such constants.
For instance, 28 as an int is internally represented as:
binary: 0000 0000 0000 0000 0000 0000 0001 1100
hex: 0 0 0 0 0 0 1 c
= 0x1c
Which means these two are equivalent:
int i = 28;
int i = 0x1c;
It is useful to express integer constants as hexadecimal when working with bit masks, because with a little habit, you can "translate" from hexadecimal to binary. For instance, when you want an integer with the last 4 bits of another one, it is more obvious what you do if you write:
i & 0xf
rather than:
i & 15
0xffffffff is -1 (or Integer.MIN_VALUE).
Everytime you calculate something, you´re dealing with numbers.
10 Dollars, 50 percent, 20 degree Celsius.
And the "nexadezimal" notations is just another way to write these numbers.
0xA Dollar, 0x32 percent, 0x14 degree Celsius.
What they mean depends on what you´re doing.
Calculating your money, temperature or something else.
When dealing with "raw byte" stuff, it´s often just more convenient
to write hex. numbers instead of normal decimal one´s,
because in such cases, they can actually improve readability.
Like 0x80000000 instead of 2147483648

Categories