I seem to be going around in circles with this one... There are many methods to achieve this and I could use a few if statements like I've done int he example below, but I want a smarter method.
Problem
The user is asked to input a value in hex, the program grabs this string and will now want to convert it into an integer, bearing in mind this is a hex value. The input could be for example:
0x00
0xf
ff
2
My Attempt
String hexString = response.getResult(); //grabs the user input
int hexInt = Integer.decode(hexString); //Doesn't work if the user doesn't add "0x" at the start
String regex = "\\s*\\b0x\\b\\s*";
String hexInt = hexString.replaceAll(regex, ""); //Doesn't like 0x for some reason
Int hexInt = Integer.valueOf(hexString,16); //Doesn't like 0x
Any ideas on how to do this smartly?
Why not just remove 0x if the string starts with it? There's no need to use a regular expression for this - just a combination of startsWith and substring is simpler to understand (IMO):
String hexString = response.getResult();
if (hexString.startsWith("0x")) {
hexString = hexString.substring(2);
}
int value = Integer.parseInt(hexString, 16);
Related
I know that I can add left zeros to String but what about Long?
I need to put left zeros until the Long size is 10 digits. For example, if it's 8 digits (12345678), it should add 2 left zeros (0012345678)
I want to add this in the getValue() method.
public Long getValue() {
// Should always be 10 digits, If it's 8, add zeros
return value;
}
I'm using spring. This issue is that the database that cuts the left zeros. Maybe is there a annotation to avoid extra code?
This is not possible. A Long does not contain data about the String representation of its value. In fact, the Long is actually stored in binary, not decimal, and the long object is unaware of this.
If you want to convert it to a String with leading zeroes, String.format("%017d" , number); will pad it to make sure it has 10 digits.
In java, a long (wrapped in a Long) will always be stored on 8 bytes,
There is no way to "add" extra zeros as they're already existing.
Either your database must change its type to String and add padding zeros when you store your Long object either change your inner code to String and add padding zeros when you pull the data from your Long in db.
You cannot because a long does not have a leading zero.
A string of characters like 0012345678 is not an integer, 12345678 is.
but there are two way in java to add leading zeroes
WAY 1: format() method
int number = 9;
String str = String.format("%04d", 9); // 0009
System.out.printf("original number %d, numeric string with padding : %s", 9, str);
WAY 2 : DecimalFormat
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // 0009
String a = df.format(99); // 0099
String b = df.format(999); // 0999
but in both case you get string instead of Long
for more reading
Try this one,
int number = 12345678;
String str = String.format("%10d", number);
System.out.println("original number %d, numeric string with padding : %s", number, str);
I am following the below method
new Biginteger(str,16).toString(2);
It works really well, but it removes leading zeros. I need output in 64 bits if input string is "3031323334353637"
But it returns 62 characters. I can use a for loop to do that. Is there any other way to do that without loop?
Goal: Converting hex to binary with leading zeros
You can pad with spaces using String.format("%64s") and then replace spaces with zeros. This has the advantage of working for any size of input, not just something in the int range. I'm guessing you're working with arbitrary inputs from your use of BigInteger...
String value = new BigInteger("3031323334353637", 16).toString(2);
System.out.println(String.format("%64s", value).replace(" ", "0"));
Output
0011000000110001001100100011001100110100001101010011011000110111
Explanation... The String.format("%64s, value) outputs the earlier String padded to fill 64 characters.
" 11000000110001001100100011001100110100001101010011011000110111"
The leading spaces are then replaced with '0' characters using String.replace(oldString, newString)
"0011000000110001001100100011001100110100001101010011011000110111"
The following may be the easiest:
new BigInteger("1" + str,16).toString(2).substring(1)
Check out this question.
You can do it using String.format():
String unpaddedBinary = new BigInteger("a12", 16).toString(2);
String paddedBinary = String.format("%064s", Integer.parseInt(unpaddedBinary, 2));
I have an application that get som Strings by JSON.
The problem is that I think that they are sending it as ASCII and the text really should be in unicode.
For example, there are parts of the string that is "\u00f6" which is the swedish letter "ö"
For example the swedish word for "buy" is "köpa" and the string I get is "k\u00f6pa"
Is there an easy way for me after I recived this String in java to convert it to the correct representation?
That is, I want to convert strings like "k\u00f6pa" to "köpa"
Thank for all help!
Well, that is easy enough, just use a JSON library. With Jackson for instance you will:
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(your, source, here);
The JsonNode will in fact be a TextNode; you can just retrieve the text as:
node.textValue()
Note that this IS NOT an "ASCII representation" of a String; it just happens that JSON strings can contain UTF-16 code unit character escapes like this one.
(you will lose the quotes around the value, though, but that is probably what you expect anyway)
The hex code is just 2 bytes of integer, which an int can handle just fine -- so you can just use Integer.parse(s, 16) where s is the string without the "\u" prefix. Then you just narrow that int to a char, which is guaranteed to fit.
Throw in some regex (to validate the string and also extract the hex code), and you're all done.
Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
Matcher m = p.matcher(arg);
if (m.matches()) {
String code = m.group(1);
int i = Integer.parseInt(code, 16);
char c = (char) i;
System.out.println(c);
}
This has been bugging me for the last few hours.
I have a long string and I want to convert it to a byte array.
I want to preserve leading zeroes too.
Have tried DatatypeConverter & BigInteger methods and cant seem to get the proper result.
which is a byte array (of hex byte values).
byte[] array = str.getBytes();
This also doesn't seem to work, with all these methods I seem to be getting decimal representation of the string. I need it to be hex.
This is what I'm using at the minute:
String line;
line = file.readLine();
long seq = Long.parseLong(line);
String hexx = Long.toHexString(seq);
byte[] out = hexx.getBytes();
BTW, i am using BufferdReader for input and RandomAccessFile for output.
Any help would be appreciated.
Ok, to convert from one radix to another. Jeez!
String str = ...
int fromRadix = ...
int toRadix = ...
String out = new BigInteger(str, fromRadix).toString(toRadix);
For example, to convert the decimal number "12345" to hex:
String str = "12345";
int fromRadix = 10;
int toRadix = 16;
String out = new BigInteger(str, fromRadix).toString(toRadix);
// yields "3039"
Go away! :P
Ok, I think I have solved this by using BigInteger and it's toByeArray method.
BigInteger linenum = new BigInteger(line,10);
writer.write(linenum.toByteArray());
Actually simple solution, thanks for your efforts guys.
I have a list of String representations of unicode hex values such as "0x20000" (𠀀) and "0x00F8" (ø) that I need to get the int code point of so that I can use functions such as:
char[] chars = Character.toChars(0x20000);
This should cover the BMP as well as supplementary characters. I cannot find any way to do it so would be glad of some help.
You can create your own NumberFormat implementation, but easier than that you can do something like this:
String hexString = "0x20000";
int hexInt = Integer.parseInt(hexString.substring(2), 16);
String stringRepresentation = new String(Character.toChars(hexInt));
System.out.println(stringRepresentation); //prints "𠀀"