i am trying to generate a hex color value from an integer input, and I'm not sure I'm using the concat method correctly. when i output the string theColor, i only get "0x", any ideas?
public String generateColor(String redVal, String blueVal,
String greenVal, String alphaVal){
String theColor = "0x";
theColor.concat(alphaVal);
theColor.concat(redVal);
theColor.concat(greenVal);
theColor.concat(blueVal);
return theColor;
}
You will need to reassign it to the theColor as concat() method returns a string with concatenation.
like
theColor = theColor.concat(alphaVal);
String's concat does not modify the original String (Strings are immutable in Java). I'd suggest using a StringBuilder here:
public String generateColor(String redVal, String blueVal, String greenVal, String alphaVal) {
StringBuilder theColor = new StringBuilder("0x")
.append(alphaVal)
.append(redVal)
.append(greenVal)
.append(blueVal);
return theColor.toString();
}
String objects in java are immutable that is operations like concat do not modify original object but create new. You need modify you code to assign modified value to theColor:
theColor = theColor.concat(alphaVal);
If your input strings are all 2-character strings with two hex digits, then you can generate the string you want really simply:
public String generateColor(String redVal, String blueVal,
String greenVal, String alphaVal) {
return "0x" + alphaVal + redVal + greenVal + blueVal;
}
No need to fool around with StringBuilder or concat.
If the input strings have been converted from integers, so that you're not sure that they are two hex digits, then the above won't work. But solutions using concat or StringBuilder's append won't work either, since they essentially do the same thing as + -- they just concatenate all the strings together.
The first question to ask is, are you converting the integers to Strings too early? If you convert the integers to strings, then you pass the strings as parameters to generateColor, and then you are concerned that the strings aren't already in the right format, then you really ought to be passing your integers to generateColor, instead of the strings, and letting generateColor convert them to the kinds of strings you need. There are several ways to do this; here's one:
public String generateColor(int redVal, int blueVal,
int greenVal, int alphaVal) {
return String.format("0x%02x%02x%02x%02x", alphaVal & 0xFF,
redVal & 0xFF, greenVal & 0xFF, blueVal & 0xFF);
}
%02x says to format the next parameter in hex (the x), into a string 2 characters wide (the 2), and padding with leading zeros instead of blanks if the value is only one hex digit (the 0). If the integer value is too big to fit into two digits, format will include three or more characters in the string, which is why I used & 0xFF on each integer to ensure that the value will not be too big. %02x does not put an 0x at the front. The format string has its own 0x to put those two characters into the result. (If desired, you can use %02X instead of %02x, which causes the hex digits A-F to appear in upper case.)
There are other ways: you could create one int from the four input integers using &, | and << bit operators, and use "0x%08x" as the format string. And there are methods besides String.format that are capable of generating hex integers.
Related
code:
String st = "abc";
String sl = st.charAt(0)+st.charAt(st.length()-1));
The second line is wrong for some reason and I don't know why
The book is wrong, and Eclipse is right.
In Java, you can write "abc" + whatever, or whatever + "abc", and it concatenates the strings -- because one side is a String.
But in st.charAt(0)+st.charAt(st.length()-1)), neither side is a String. They're both chars. So Java won't give you a String back.
Instead, Java will actually technically give you an int. Here are the gritty details from the Java Language Specification, which describes exactly how Java works:
JLS 4.2 specifies that char is considered a numeric type.
JLS 15.18.2 specifies what + does to values of numeric types.
In particular, it specifies that the first thing done to them is binary numeric promotion, which converts both chars to int by JLS 5.6.2. Then it adds them, and the result is still an int.
To get what you want to happen, probably the simplest solution is to write
String sl = st.charAt(0) + "" + st.charAt(st.length() - 1));
Because charAt returns char [ int ]
use this code :
String st = "abc";
StringBuilder str = new StringBuilder();
str.append(st.charAt(0));
str.append(st.charAt(st.length() - 1));
System.out.println(str.toString());
append method accept the char, or string, ..
well this is what it says: "- Type mismatch: cannot convert from int to String"
Meaning exactly what #Jaime said. If I remember correctly, a char is technically represented by an integer value. (i.e. 'a' + 1 = 'b'). So you're adding two char values, which isn't the same thing as adding two strings together, or even concatenating two char values. One fix would be to use String.valueOf(st.charAt(0)) + String.valueOf(st.charAt(st.length()-1))) to concatenate the two char values.
I have a function for hashing passwords, that returns a byte[] with entries using the full range of the byte datatype from -128 to 127. I have tried to convert the byte[] to a String using new String(byte_array, StandardCharsets.UTF_8);. This does return a String - however it can not properly encode negative numbers - hence it encodes them to a "�" character. When comparing two of those characters using: new String(new byte[]{-1}, StandardCharsets.UTF_8).equals(new String(new byte[]{-2}, StandardCharsets.UTF_8)) it turns out the String representation for all negative numbers is equal as the expression above returns true. While this doesn't fully ruin my hashing functionality as the hash of the same expression will still always yield the same result, this is obviously not what I want as it increases the chance of two different inputs yielding the same output drastically.
Is there some easy fix for this or any alternative idea how to convert the byte[] to a String? For context I want to use the String to later write it to a file to store it in a file and later read it again to compare it to other hashes.
Edit: After a bit of trying around with the tips from the comments my solution is to convert the byte[] to a char[] and add 128 to every value. The char array can then easily be converted to a String or be written to a file directly (byteHash is the byte[]):
char[] charHash = new char[byteHash.length];
for(int i = 0; i < byteHash.length; i++){
charHash[i] = (char) (byteHash[i]+128);
}
return new String(charHash);
I do not really like the solution but it works.
The appropriate solution to this is to use an encoding like hexadecimal (https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html) or Base64 (https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) to convert an arbitrary byte sequence to a string reversibly.
Well, I have a string in my Java code that needs to be converted into an integer with padding of 10.
Ex. Consider this is the string... Str = "52112"
I need to convert this string into an integer and the result should be like "0000052112". The result should be an integer. Can anyone help me with this, please?
As far as I know you cannot have an integer typed variable with leading zeros. You can pad the number with zeros but then it will become a String.
Take a look at:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#leftPad(java.lang.String,%20int)
In order to conform to the signature you have to convert the number to a string first, but that is no great deal.
The leading zeroes have no meaning if the data type you require is an Integer (or any other numeric type). If on the other hand you need a String with leading zeroes, you can use this (works only if required string length is >= number of digits of the number you want to pad) :
String myNumber = Integer.toString(42);
String myNumberWithLeadingZeroes = "0000000000" + myNumber;
// 10 zeroes if you need a string of length 10 in the end
myNumberWithLeadingZeroes = myNumberWithLeadingZeroes.substring(myNumber.length());
I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others
I have hexadecimal String eg. "0x103E" , I want to convert it into integer.
Means String no = "0x103E";
to int hexNo = 0x103E;
I tried Integer.parseInt("0x103E",16); but it gives number format exception.
How do I achieve this ?
You just need to leave out the "0x" part (since it's not actually part of the number).
You also need to make sure that the number you are parsing actually fits into an integer which is 4 bytes long in Java, so it needs to be shorter than 8 digits as a hex number.
No need to remove the "0x" prefix; just use Integer.decode instead of Integer.parseInt:
int x = Integer.decode("0x103E");
System.out.printf("%X%n", x);