Java: Problems converting char to int [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java char array to int
I have the following code, where stackCells is an ArrayList object:
int[] stackCell = {0, 0};
if (!stackCells.isEmpty()) {
String stackCellString = stackCells.get(0);
stackCell[0] = stackCellString.charAt(0);
stackCell[1] = stackCellString.charAt(1);
}
So the problem I am encountering is that stackCell is not interpreting the character as an int. For example, the value of stackCellString should be "88". However, when I use chartAt(0) and charAt(1), I get an int value of 56. If I use those same calls inside a System.out.println(stackCellString.charAt(0) + stackCellString.charAt(1)) command, I get the correct result (i.e. "88").

It's interpreting the character as an int in the following way:
56 is the ASCII code for the character '8'.
If you want to grab the numeric digits from the string, you will need to use something like Integer.parseInt() as one of the comments mentioned.
A more efficient solution might be to do some math based on the ASCII code. If you know all of the characters are decimal digits, you could do (code - 48) to get the digit (where code is the ASCII code). For instance, (56 - 48) = 8, which is what you want here.

56 is the ASCII code of the digit 8. To get what you want, you could do this:
stackCell[0] = stackCellString.charAt(0) - '0';
stackCell[1] = stackCellString.charAt(1) - '0';

String stackCellString="88";
stackCell[0] = stackCellString.charAt(0);
stackCell[1] = stackCellString.charAt(1);
System.out.println(stackCell[0]);
System.out.println(stackCell[1]);
System.out.println(stackCell[0]+stackCell[1]);
System.out.println(stackCellString.charAt(0) + stackCellString.charAt(1));
output:
56
56
112
112
You are not returning the charAt as its character representation.
If you want it to return "88" you need to do this:
stackCellString.subString(0,1) + stackCellString.subString(1,2);
Another work around is this:
"" + stackCellString.charAt(0) + stackCellString.charAt(1);

Related

How can I pad a hexadecimal digit with 0 in java? [duplicate]

This question already has answers here:
Integer to two digits hex in Java
(7 answers)
Closed 1 year ago.
I'm trying to pad a hexadecimal digit with 0's in the beginning so that the length of it is always 4. For example, the FF is going to be padded as 00FF. I have tried to use String.format("%04d", number) but it didn't work as my hexadecimal digit is actually a string.
I have also tried using StringUtils.leftPad() but for some reason, IntelliJ couldn't detect it.
Please note my count is going to change, but I haven't represented it here as I'm yet to implement it. This is my sample code. Thanks.
public static void main(String[] args) {
int count = 0;
String orderID = Integer.toHexString(count).toUpperCase();
System.out.println(String.format("%04d", Integer.valueOf(orderID)));
}
String.format("%04x", 255)
with output
00ff
(or use X for uppercases hex digits)
As #user16320675 point, more info about Formatter here.

Java Hexadecimal to Decimal conversion: Custom Logic

I am trying to figure out how to convert hex into a string and integer so I can manipulate an RGB light on my arduino micro-controller through it's serialport. I found a good example on the java website, but I'm having a difficult time understanding some of the methods and I am getting hung up. I could easily just copy-paste this code and have it work but I want to fully understand it. I will add comments to my understandings and hopefully someone can provide some feedback.
public class HexToDecimalExample3{
public static int getDecimal(String hex){ //this is the function which we will call later and they are declaring string hex here. Can we declare string hex inside the scope..?
String digits = "0123456789ABCDEF"; //declaring string "digits" with all possible inputs in linear order for later indexing
hex = hex.toUpperCase(); //converting string to uppercase, just "in case"
int val = 0; //declaring int val. I don't get this part.
for (int i = 0; i < hex.length(); i++) //hex.length is how long the string is I think, so we don't finish the loop until all letters in string is done. pls validate this
{
char c = hex.charAt(i); //char is completely new to me. Are we taking the characters from the string 'hex' and making an indexed array of a sort? It seems similar to indexOf but non-linear? help me understand this..
int d = digits.indexOf(c); //indexing linearly where 0=1 and A=11 and storing to an integer variable
val = 16*val + d; //How do we multiply 16(bits) by val=0 to get a converted value? I do not get this..
}
return val;
}
public static void main(String args[]){
System.out.println("Decimal of a is: "+getDecimal("a")); //printing the conversions out.
System.out.println("Decimal of f is: "+getDecimal("f"));
System.out.println("Decimal of 121 is: "+getDecimal("121"));
}}
To summerize the comments, it's primarily the char c = hex.charAt(i); AND the val = 16*val + d; parts I don't understand.
Ok, let's go line for line
public static int getDecimal(String hex)
hex is the parameter, it needs to be declared there, so you can pass a String when you call the function.
String digits = "0123456789ABCDEF";
Yes, this declares a string with all characters which can occur in a hexadecimal number.
hex = hex.toUpperCase();
It converts the letters in the hex-String to upper case, so that it is consistent, i.e. you always have F and never f, no matter which is being input.
int val = 0;
This is the variable where the corresponding decimal value will later be in. We will do our calculations with this variable.
for (int i = 0; i < hex.length(); i++)
hex.length() is the number of characters in the hex-String provided. We execute the code inside this for loop once per character.
char c = hex.charAt(i);
Yes, char represents a single character. We retrieve the character from the hex-String at index i, so in the first iteration it is the first character, in the second iteration the second character and so on.
int d = digits.indexOf(c);
We look which index the character has in the digit-String. In that way we determine the decimal representation of this specific digit. Like 0-9 stay 0-9 and F becomes a 15.
val = 16*val + d;
Let's think about what we have to do. We have the decimal value of the digit. But in hexadecimal we have this digit at a specific position with which it gets multiplied. Like the '1' in '100' is actually not a 1, but 100 * 1 because it is at this position.
10 in hexadecimal is 16 in decimal, because we have 1 * 16. Now the approach here is a little bit complicated. val is not uninitialized. val is 0 at the beginning and then contains the cumulated values from the previous iterations. Since the first character in the String is the highest position we don't know directly with what we have to multiply, because we don't know how many digits the number has (actually we do, but this approach doesn't use this). So we just add the digit value to it. In the consecutive iterations it will get multiplied by 16 to scale it up to the corresponding digit base value. Let me show you an example:
Take 25F as hex number. Now the first iteration takes the 2 and converts it to a 2 and adds it to val. The 16 * val resolves to 0 so is not effective in the first time.
The next iteration multiplies the 2 with 16 and takes the 5 (converted to 5) and adds it to val. So now we have (I split it mathematically so you understand it):
2 * 16 + 5
Next we get the F which is decimal 15. We multiply val by 16 and add the 15.
We get 2 * 256 + 5 * 16 + 16 (* 1), which is actually how you calculate the decimal value of this hex value mathematically.
Another possibility to compute val is:
val += Math.pow(16, hex.length() - i - 1) * d;

String Contatenation with primitives in java

I just recently started learning Basics in Java, and was testing around initializing a string variable by concatenating primitive variables.
public class Main{
public static void main(String[] args){
byte lbyte = 3;
short lshort = 1;
int lint = 1;
long llong = 0;
float lfloat = 2.0f;
double ldouble = lfloat;
char lchar = 'H';
boolean lbool = true;
String lstring = " w0r1d ";
String lOutput = lchar+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;
System.out.println(lOutput);
}
}
In this code, my objective was to create a string that would output:
H3110 w0r1d 2.0 true
However, when i run it the output is: 77 w0r1d 2.0 true
The unexpected result is the 77, while the rest is fine. Even if i would assume the number variables would get added, it would only be a total of 5. The variable lchar is also apparently "absorbed" into the numbers.
Where did the 77 come from and what happened to the H in lchar?
Edit: the goal is to use as much primitive variables as possible in the concatenation.
Edit2: Thanks for all the helpful answers.
The ASCII / Unicode value for 'H' is 72. The additions are processed left to right, so lchar + lbyte is 'H' + (byte) 3 which is equal to 72 + 3.
You'll only get a string result from + if one of the operands is a string. That doesn't happen until you finally concatenate lstring, which explains why all of the numerical (and the char) variables are added together to get 77. Everything to the right of lstring is concatenated one by one, each converted to a string, since the left hand operands of all those +s are all strings at that point.
A quick fix is to start with "" to force everything to be done with strings.
String lOutput = ""+lchar+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;
The 77 came from when you were adding the chars. When adding chars it adds their values since they act like integers. Also the other variables which are numbers might have added together. 'H' = 72 in java and 72 + 3 = 75 and 75 + 1 = 76 and finally 76 + 1 = 77.
To fix this you can put "" at the beginning of where you are building your string.
Fix:
String lOutput = ""+lchar+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;
Java evaluates expressions like that left to right so what's happening is that you're telling Java to add a char and a byte together and Java will then take the integer value of the character (72) and add the integer value of the byte (3) to it.
So what you're really telling Java is to do this:
String lOutput = (72+3+1+1+0)+" w0r1d"+2.0+' '+true;
When Java comes to +" w0r1d" it will convert the first part into a String and concatenate them, but before that you're adding types where + is defined as addition and therefore Java will sum them up to 77.
To get the desired behaviour you need to start out with a String, so doing this will work as you want it to:
String lOutput = String.valueOf(lchar)+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;
This is for automatic type conversion.Look the in the ASCI chart the integer representation of capital 'H' is 72. At first the 'H' is upgraded to int from char and then it is concatenated with the string right to it

XOR hex ascii values of letters

I'm trying to complete some homework and am totally stumped. The function I need to perform is, given the hexadecimal value of a character, xor it with another hex value to verify a known end value.
Giving a simple example (the one given to me), I know that the ascii value of 'Bob' would be [42,6F,62], and 'Eve' would be [45,76,65]. I have to XOR 'Bob''s value with [07,16,17] to get 'Eve'.
I thought that xor was simply addition modulo base, but simply using the Microsoft Calculator: (42 + 45) mod 16 = 3 but 42 XOR 45 = 7. I do not understand how else the XOR function would be done. Can someone please explain?
Thanks in advance
I tried
float l = (6F)^(16);
System.out.println(l);
and got this exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - bad operand types for binary operator '^'
first type: float
second type: double
at p2p_example.P2P_Example.main(P2P_Example.java:40)
Java Result: 1
XOR is a bitwise exclusive-or,
42 = 1000010
45 = 1000101
7 = 0000111
That is a one if there is one (and only one) one in the two bits being XORd. For Java, you can use parseInt and pass in the radix, for example
public static void main(String[] args) {
int a = Integer.parseInt("42", 16);
int b = Integer.parseInt("45", 16);
System.out.println(Integer.toString(a ^ b, 16));
}
prints
7
0x42 + 0x45 = 0x87
= 135
135 % 16 = 7 = 0x07
I think you're getting confused between hex and decimal bases (though (42+45)%16 also happens to be 7 in decimal; so maybe you're just doing your math wrong?)

Can I multiply charAt in Java?

When I try to multiply charAt I received "big" number:
String s = "25999993654";
System.out.println(s.charAt(0)+s.charAt(1));
Result : 103
But when I want to receive only one number it's OK .
On the JAVA documentation:
the character at the specified index of this string. The first character is at index 0.
So I need explanation or solution (I think that I should convert string to int , but it seems to me that is unnesessary work)
char is an integral type. The value of s.charAt(0) in your example is the char version of the number 50 (the character code for '2'). s.charAt(1) is (char)53. When you use + on them, they're converted to ints, and you end up with 103 (not 100).
If you're trying to use the numbers 2 and 5, yes, you'll have to parse them. Or if you know they're standard ASCII-style digits (character codes 48 through 57, inclusive), you can just subtract 48 from them (as 48 is the character code for '0'). Or better yet, as Peter Lawrey points out elsewhere, use Character.getNumericValue, which handles a broader range of characters.
Yes - you should parse extracted digit or use ASCII chart feature and substract 48:
public final class Test {
public static void main(String[] a) {
String s = "25999993654";
System.out.println(intAt(s, 0) + intAt(s, 1));
}
public static int intAt(String s, int index) {
return Integer.parseInt(""+s.charAt(index));
//or
//return (int) s.charAt(index) - 48;
}
}

Categories

Resources