I am performing some bit wise operations(& and |) on hexadecimal numbers.
Integer number1 = 0X00020000;
Integer number2 = 0X00000001;
System.out.println(number1);
System.out.println(number1 | number2);
System.out.println(number1 + number2);
Output :
131072
131073
131073
0X00020000 automatically got converted to 131072.
I am getting right answer but I am curious to know how & WHY Java converts hexadecimal number to decimal number.
I know how to convert hexadecimal number to decimal number.
0X00020000 will be converted to decimal as follows,
(2 X 16^4) + (0 X 16^3) + (0 X 16^2) + (0 X 16^1) + (0 X 16^0)
= (2 X 65536) + 0 + 0 + 0 + 0
= 131072
The right way to look at this is not as something being converted, but rather the way something is being displayed.
There is only one value stored for the variable, no matter how to write it in your source code. Write it anyway you like; once it is stored in memory, Java neither knows or cares what it looked like in your source code.
System.out.println renders the integer value, as a string, using decimal by default. Try System.out.printf("%x\n", number1); to see it rendered in hex.
Just keep in mind there is a big difference between the integer value and its string representation. If there is anything "converted" here, it's a conversion from an string (in your source) to an integer value (represented in memory) to a string (written to standard output). The last step uses decimal numerals by default.
Related
Don't understand Java's syntax. How to convert: "%6d %7.1f %5.1f" to C# equivalent ?
I keep getting this print out in C#: %6d %7.1f %5.1f
Tried:
"{0:d6} {7:1f} {5:1f}"
But, ran into an exception.
Exception:
Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0, Object arg1, Object arg2)
at experiment.Main(String[] args)
The Java code:
String.format("%6d %7.1f %5.1f", int, double, double/double);
It's obvious what values will be generated based on variable data types.
EDIT: I just looked at, Convert this line of Java code to C# code
C#
String.Format("{0:x2}", arrayOfByte[i]);
Java
String.format("%02x", arrayOfByte[i]);
PLEASE. PLEASE. PLEASE. DO not close this. Kindly. Please.
NOTE: Completely rewrote my original answer based on a (hopefully) better understanding of the Java format specifiers.
Based on my (Google-limited understanding), %6d, %7.1f and %5.1f correspond to the following:
An integer with up to 6 characters, padded if less than 6.
A float with up to 7 characters (including the decimal point and decimal portion) with a precision of 1.
A float with up to 5 characters (including the decimal point and decimal portion) with a precision of 1.
You can accomplish this with C#'s String.Format, like this:
var newString = String.Format("{0,6:d} {1,7:f1}, {2,5:f1}", 605, 20.5, 8.22);
This will result in the following string:
" 605 20.5 8.22"
The first digit in each placeholder group (defined by { and }) corresponds to the argument passed in after the string:
0 = 605
1 = 20.5
2 = 8.22
The second digit, after the , refers to the length of the string (including decimal points and decimal portions).
6 = 6 characters for the integer
7 = 7 characters for the float
5 = 5 characters for the float
The letters and numbers after the : are the format specifiers.
d = integer
f1 = floating with a precision of 1.
Which produces the string above, as follows:
{0,6:d} turns 605 into " 605" (3 leading spaces due to the 6 before the :)
{1,7:f1} turns 20.5 into " 20.5" (3 leading spaces due to the 7 before the :)
{2,5:f1} turns 8.22 into " 8.2" (1 leading space due to the 5 before the : and 1 decimal number due to the precision).
As I said earlier, check String.Format and Standard Numeric Format Strings for more information.
Starting from C# 6. you can use interpolation.
For your case you may wanted to try the following:
string formattedString = $"{0:d6} {7.1:f} {5.1:f}";
before C# 6 you can try the following:
string formattedString = String.Format("{0:d6} {1:f} {2:f}", 0, 7.1, 5.1);
I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.
Is this Java Api's bug?
int i = 0xD3951892;
System.out.println(i); // -745203566
String binString = Integer.toBinaryString(i);
int radix = 2;
int j = Integer.valueOf(binString, radix );
Assertions.assertThat(j).isEqualTo(i);
I expect it to be true without any question. But it throws below exception:
java.lang.NumberFormatException: For input string: "11010011100101010001100010010010"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.valueOf(Integer.java:556)
at com.zhugw.temp.IntegerTest.test_valueof_binary_string(IntegerTest.java:14)
So if I have a binary String , e.g. 11010011100101010001100010010010, How can I get its decimal number(-745203566) in Java? DIY? Write code to implement below equation?
Integer.valueOf(String, int radix) and Integer.parseInt(String, int radix) will only parse numbers of value -2 147 483 648 to 2 147 483 647, i.e. the values of 32-bit signed integers.
These functions cannot interpret two's complement numbers for binary (radix = 2), because the string being passed can be of any length, and so a leading 1 could be part of the number or the sign bit. I guess Java's developers decided that the most logical way to proceed is to never accept two's complement, rather than assume that a 32nd bit is a sign bit.
They read your input binary string as unsigned 3 549 763 730 (bigger than max int value). To read a negative value, you'd want to give a positive binary number with a - sign in front. For example for -5:
Integer.parseInt("1011", 2); // 11
// Even if you extended the 1s to try and make two's complement of 5,
// it would always read it as a positive binary value
Integer.parseInt("-101", 2); // -5, this is right
Solutions:
I suggest, first, that if you can store it as a positive number with extra sign information on your own (e.g. a - symbol), do that. For example:
String binString;
if(i < 0)
binString = "-" + Integer.toBinaryString(-i);
else // positive i
binString = Integer.toBinaryString(i);
If you need to use signed binary strings, in order to take a negative number in binary two's complement form (as a string) and parse it to an int, I suggest you take the two's complement manually, convert that into int, and then correct the sign. Recall that two's complement = one's complement + 1, and one's complement is just reverse each bit.
As an example implementation:
String binString = "11010011100101010001100010010010";
StringBuilder onesComplementBuilder = new StringBuilder();
for(char bit : binString.toCharArray()) {
// if bit is '0', append a 1. if bit is '1', append a 0.
onesComplementBuilder.append((bit == '0') ? 1 : 0);
}
String onesComplement = onesComplementBuilder.toString();
System.out.println(onesComplement); // should be the NOT of binString
int converted = Integer.valueOf(onesComplement, 2);
// two's complement = one's complement + 1. This is the positive value
// of our original binary string, so make it negative again.
int value = -(converted + 1);
You could also write your own version of Integer.parseInt for 32-bit two's complement binary numbers. This, of course, assumes you're not using Java 8 and can't just use Integer.parseUnsignedInt, which #llogiq pointed out while I was typing this.
EDIT: You could also use Long.parseLong(String, 2) first, then calculate the two's complement (and mask it by 0xFFFFFFFF), then downgrade the long down to int. Faster to write, probably faster code.
The API docs for Integer.toBinaryString(..) explicitly state:
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 8).
(as of Java 8u25) I think this is a documentation error, and it should read Integer.parseUnsignedInt(s, 2). Note the Unsigned. This is because the toBinaryString output will include the sign bit.
Edit: Note that even though this looks like it would produce an unsigned value, it isn't. This is because Java does not really have a notion of unsigned values, only a few static methods to work with ints as if they were unsigned.
In the following code intArray[i] stores RGB values of pixels in hex format(eg:0xffff0000) .... The method hsvToRgb() gives bak an integer value of RGB (eg:15777252) but i need back the rgb value in the original hex format after changes.
The second line gives me that but its a string ....What do i do to store this string value back into the array? ... please help me.
int disco = hsvToRgb(hsv);
hexColor = String.format("0x%06X", (0xffffff & disco));
intArray[i] = Integer.valueOf(String.valueOf(disco), 16);
There's no such thing as a "hex format" integer versus a "decimal format" integer. The bit/byte representation of the value is the same. For example, the decimal value 15,777,252 is the hex value 0xF0BDE4. (You can use Google to convert: search "15777252 in hex").
You can use the disco value directly. If you want to print it out in a hex representation, use Integer.toHexString().
Regarding the format. Think of it like this ... The computer represents the value as a series of bits. By way of example, let's pick a random number and represent it using 8 bits: 01110101. Using a bit string to represent bigger numbers would get very long very quickly, so hexadecimal is often used. The hex equivalent is: 65. By convention, we usually precede the value by 0x when it's in hex. That gives us 0x65. Non-programmers tend to deal more naturally in base 10 however (rather than base 16). The same number in base 10 is 101.
You can see this with some code:
final int value = 0x65; // we can declare it in hex
final int sameValue = 101; // or in decimal
System.out.println(value); // output in base 10; prints "101"
System.out.println(Integer.toHexString(value)); // output in base 16; prints "65"
System.out.println(Integer.toBinaryString(value)); // output in base 2; prints "1100101"
System.out.println(""+(value == sameValue)); // prints "true"
Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation?
BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros();
System.out.println("value: " + bigDecimal);
use bigDecimal.toPlainString():
BigDecimal bigDecimal = BigDecimal.valueOf(100000.0)
.multiply(BigDecimal.valueOf(100d))
.stripTrailingZeros();
System.out.println("plain : " + bigDecimal.toPlainString());
System.out.println("scientific : " + bigDecimal.toEngineeringString());
outputs:
plain : 10000000
scientific : 10E+6
It's the implicit .toString() conversion that is happening when you pass the result into System.out.println().
The exact rationale for the behaviour of BigDecimal.toString() is explained in the API doc in great (and near incomprehensible) detail.
To get a consistent (and locale-sensitive) textual representation, you should use DecimalFormat.
It's basically because you don't have enough significant digits. If you multiply something that only has 1 significant digit with 100, then you get something with only 1 significant digit. If it shows "10" then that basically says that it has 2 significant digits. The way to show it only has 1 significant digit is to show "1 x 10^1".
The following two decimals have the same value (10), but different "scales" (where they start counting significant digits; the top has 2 sig figs, the bottom has 1):
System.out.println(new BigDecimal(BigInteger.TEN, 0)); // prints 10
System.out.println(new BigDecimal(BigInteger.ONE, -1)); // prints 1E+1