I want to transform an int to a String such that:
0 -> "a"
1 -> "b"
2 -> "c"
and so on...
How can I do this?
You can convert from the character literal:
int input = 0;
String output = new Character((char) (input + 'a')).toString();
Your question is a little unclear, but it sounds like you want to be able to convert integers 0-25 to their corresponding alphabetical characters. If that's the case, your best bet logically is probably to use an enum. Though I may not be fully seeing the purpose of what you're trying to do (which is likely).
You could also write a utility method which just has a big switch statement to convert them.
An alternate method, for some java library flavor:
int value;
String output = Integer.toString(value + 10, 36);
which uses a radix of 36 to locate the right letter.
Related
Is there any way that I can use a hashcode of a string in java, and recreate that string?
e.g. something like this:
String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
System.out.println("Hmm, something went wrong: " + myNewstring);
I say this, because I must turn a string into an integer value, and reconstruct that string from that integer value.
This is impossible. The hash code for String is lossy; many String values will result in the same hash code. An integer has 32 bit positions and each position has two values. There's no way to map even just the 32-character strings (for instance) (each character having lots of possibilities) into 32 bits without collisions. They just won't fit.
If you want to use arbitrary precision arithmetic (say, BigInteger), then you can just take each character as an integer and concatenate them all together. Voilà.
No. Multiple Strings can have the same hash code. In theory you could create all the Strings that have have that hash code, but it would be near infinite.
Impossible I'm afraid. Think about it, a hashcode is a long value i.e. 8 bytes. A string maybe less than this but also could be much longer, you cannot squeeze a longer string into 8 bytes without losing something.
The Java hashcode algorithm sums every 8th byte if I remember correctly so you'd lose 7 out of 8 bytes. If your strings are all very short then you could encode them as an int or a long without losing anything.
For example, "1019744689" and "123926772" both have a hashcode of -1727003481. This proves that for any integer, you might get a different result (i.e. reversehashcode(hashcode(string)) != string).
Let's assume the string consists only of letters, digits and punctuation, so there are about 70 possible characters.
log_70{2^32} = 5.22...
This means for any given integer you will find a 5- or 6-character string with this as its hash code. So, retrieving "Hello World": impossible; but "Hello" might work if you're lucky.
You could do something like this:
char[] chars = "String here".toCharArray();
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = (int)chars[i];
}
Then:
char[] chars = new char[ints.length]
for (int i = 0; i < chars.length; i++) {
chars[i] = (char)ints[i];
}
String final = new String(chars);
I have not actually tested this yet... It is just "concept" code.
PS: I tried searching many existing questions here on Stackoverflow, however it
only added chaos to my query!
10101
11100
11010
00101
Consider this as a sample Input, which I need to read as BinaryString one by one! Then I need to represent them as an Integer.
Obviously int x = 20 initializes x as a decimal Integer,
and I read from other questions that int y = 0b101 initializes y as a binary Integer.
Now, The question is: If I have a binaryString, how do I cast it into an int like with a preceding 0b . My objectives following this is to perform bit level OR and XOR operations.
ie from the above input, I need to do 10101 ^ 11100
Let me know if this is the right way to approach a problem like this, Thanks!
If I have understood your question correctly, you want to know how to represent Binary Strings as Integer.
Well, you can perform this task for conversion of Binary String to Integer:
String input = "0b1001";
String temp = input.substring(2);
int foo = Integer.parseInt(temp, 2);
Alternately, to switch back :
String temp = Integer.toBinaryString(foo);
from the above input, I need to do 10101 ^ 11100.
You can achieve the same using proper decimal representation of integer. If you want to re-invent the wheel, then
first convert the decimal representation of the given number to Binary String(using step 2);
then convert to integer value using step 1;
repeat steps 1 and 2 for the second number; and
finally, perform the XOR operation over them.
But, I don't see how it'll be performing/calculating differently. It'd still be stored as the same integer. It is just that you will get extra satisfaction(on your part) that the number was read as an integer and then converted to Binary representation of that number.
Try Integer.parseInt(String s, int radix). It will throw an exception if the binary string is invalid, so you might want to validate the input.
String binary = "10001";
int asInt = Integer.parseInt(binary, 2); // 17
int supports ^ (bitwise XOR) operator. All you have to do is convert your binary strings to int variables and perform the desired operations.
I need to parse the value of a label so that it can be stored as an Integer
JLabel lblSeatNo;
int seatNo;
seatNo = Integer.parseInt(lblSeatNo.getText());
It has worked other times I have used with method, however now I am getting a Number Format Exception and I don't understand why.
If it helps with value of the label can vary, it's general format is something like: "A131" or "B504"
Thankyou.
Assuming you want this as a hex number (that is base 16), you must supply the radix to your parseInt call -
seatNo = Integer.parseInt(lblSeatNo.getText(), 16);
if you want the decimal value (e.g. base 10) and to skip the letter, you could do
seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));
Try int value = Integer.parseInt(hexString, 16); if you know that the string representation will always be hexadecimal. You might also want to check the documentation of the method in question.
Depends on what you are wanting:
If you want to just parse the numbers (not including a, b, etc) then you have to call substring to remove the letter.
if the letter is meant to be there as a hex number then you can call
Integer.parseInt(hexNo, 16)
follow this link
How to parse hex color String to Integer
eg. Integer.parseInt(myHexValue,16)
From your comments it seems like you want to extract just the number from the Seat label. But since you say that you also need to recreate the seat label then in your object you may also want to add a String for the row which will contain the Letter
So you could do something like this (assuming only ever a single letter)
int seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));
String row = lblSeatNo.getText().subString(0,1);
Then to get the label again
String label = row + seatNo;
I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}
Integer.toBinaryString(data)
gives me a binary String representation of my array data.
However I would like a simple way to add leading zeros to it, since a byte array equal to zero gives me a "0" String.
I'd like a one-liner like this:
String dataStr = Integer.toBinaryString(data).equals("0") ? String.format(format, Integer.toBinaryString(data)) : Integer.toBinaryString(data);
Is String.format() the correct approach? If yes, what format String should I use?
Thanks in advance!
Edit: The data array is of dynamic length, so should the number of leading zeros.
For padding with, say, 5 leading zeroes, this will work:
String.format("%5s", Integer.toBinaryString(data)).replace(' ', '0');
You didn't specify the expected length of the string, in the sample code above I used 5, replace it with the proper value.
EDIT
I just noticed the comments. Sure you can build the pattern dynamically, but at some point you have to know the maximum expected size, depending on your problem, you'll know how to determine the value:
String formatPattern = "%" + maximumExpectedSize + "s";
This is what you asked for—padding is added only when the value is zero.
String s = (data == 0) ? String.format("%0" + len + 'd', 0) : Integer.toBinaryString(data);
If what you really want is for all binary values to be padded so that they are the same length, I use something like this:
String pad = String.format("%0" + len + 'd', 0);
String s = Integer.toBinaryString(data);
s = pad.substring(s.length()) + s;
Using String.format() directly would be the best, but it only supports decimal, hexadecimal, and octal, not binary.
You could override that function in your own class:
public static String toBinaryString(int x){
byte[] b = new byte[32]; // 32 bits per int
int pos = 0;
do{
x = x >> 1; // /2
b[31-pos++] = (byte)(x % 2);
}while(x > 0);
return Arrays.toString(b);
}
would this satisfy your needs?
String dataStr = data == 0 ? "00" + Integer.toBinaryString(data) : Integer.toBinaryString(data);
edit: noticed the comment about dynamic length:
probably some of the other answers are more suited:)
This, in concept, is almost same as #Óscar López answer, but different methods are used, so i thought i should post it. Hope this is fine.
1] Building the format string
String format = "%0" + totalDigits + "d";
2] Integer to Binary Conversion
String dataStr = Integer.toBinaryString(data);
3] Padding with Leading Zeros
dataStr = String.format(format, new Integer(dataStr));
The major difference here is the 3rd step. I believe, its actually a hack.
#erickson is right in String.format() not supporting binary, hence, i converted the binary number to an integer (not its equivalent), i.e., "100" will be converted to hundred (100), not four(4). I then used normal formatting.
Not sure about how much optimized this code is, but, i think its more easy to read, but, maybe, its just me.
EDIT
1] Buffer Over-run is possible for longer binary strings. Long can be used, but, even that has limitations.
2] BigInteger can be used, but, I'm sure, it will be the costliest at runtime compared to all the other methods.
So, it seems, unless only shorter binary strings are expected, replace() is the better method.
Seniors,
please correct me if I'm wrong.
Thanks.