Writing string to byte array in java - java

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.

Related

Smartly Decoding Hex Input (e.g 0x32, 0x3, 32 etc...)

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);

how to reduce length of UUID generated using randomUUID( )

I have a short utility in which I am generating a UUID using randomUUID().
String uuid = UUID.randomUUID().toString();
However, the uuid generated is too long which is 36 in length.
Is there any way I can reduce the length of the UUID from 36 to near 16 or make the UUID length dynamic?
If you don't need it to be unique, you can use any length you like.
For example, you can do this.
Random rand = new Random();
char[] chars = new char[16];
for(int i=0;i<chars.length;i++) {
chars[i] = (char) rand.nextInt(65536);
if (!Character.isValidCodePoint(chars[i]))
i--;
}
String s = new String(chars);
This will give you almost the same degree of randomness but will use every possible character between \u0000 and \ufffd
If you need printable ASCII characters you can make it as short as you like but the likelihood of uniqueness drops significantly. What can do is use base 36 instead of base 16
UUID uuid = UUID.randomUUID();
String s = Long.toString(uuid.getMostSignificantBits(), 36) + '-' + Long.toString(uuid.getLeastSignificantBits(), 36);
This will 26 characters on average, at most 27 character.
You can use base64 encoding and reduce it to 22 characters.
If you use base94 you can get it does to 20 characters.
If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes.
If you don't care about Strings you can use 16, 8-bit bytes.
String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
String uuid16digits = uuid.substring(uuid.length() - 16);
This will return the last 16 digits of actual uuid.
Convert it from base 16(0-9,A-F) to base 36(0-9,A-Z).. You could go to base 62 (0-9, A-Z, a-z) but if you need to read it over a phone or something then this can be error prone.
https://github.com/salieri/uuid-encoder is a lib that might work for you...
Also this means you still have a GUID -you haven't truncated it like the other answers
You can use the substring method to decrease the string length while generating uuid.
UUID.randomUUID().toString().substring(0, 5)
You could evaluate using the ${__time()} function
The following snippet is a dynamic UUID code. By default, the legth of the UUID depends on bits but the function randomly chooses characters from the UUID
public String myUUID(int length) {
String allChars = UUID.randomUUID().toString().replace("-", "");
Random random = new Random();
char[] otp = new char[length];
for (int i = 0; i < length; i++) {
otp[i] =
allChars.charAt(random.nextInt(allChars.length()));
}
return String.valueOf(otp);
}
Yes,You can create by using this function.
public static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes()).getLong();
return Long.toString(l, Character.MAX_RADIX);
}

Big Integer and Hex Strings in java

I am trying to convert a hex string to a decimal value (integer). Having found
int i = Integer.valueOf(s, 16).intValue();
here,
i achieved to convert a hex string up to a certain size to an int.
But when the string gets larger, then the int or long does not work, so i tried BigInteger.
Unfortunately, it returns an error :
JEncrytion.java:186: <identifier> expected
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: illegal start of expression
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: not a statement
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
The code fragment is :
String[] parts = final_key.split("#") ;
String part_fixed = parts[0];
String part_user = parts[1];
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
System.out.println("");
System.out.println("hex value of the key : " + part_user_hex);
Any ideas what to do?
3 errors
You're trying to assign a primitive int value to a BigInteger reference variable. That won't work. You want to do
BigInteger hex = new BigInteger("45ffaaaaa", 16);
Also, you've named your class JEncrytion instead of JEncryption.

How to convert hex strings to byte values in Java

I have a String array.
I want to convert it to byte array.
I use the Java program.
For example:
String str[] = {"aa", "55"};
convert to:
byte new[] = {(byte)0xaa, (byte)0x55};
What can I do?
String str = "Your string";
byte[] array = str.getBytes();
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
check that a string consists only of 2 characters
these chars are in '0'..'9' or 'a'..'f' interval (take their case into account
as well)
convert each character to a corresponding number, subtracting code value of '0' or 'a'
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
Convert string to Byte-Array:
byte[] theByteArray = stringToConvert.getBytes();
Convert String to Byte:
String str = "aa";
byte b = Byte.valueOf(str);
You can try something similar to this :
String s = "65";
byte value = Byte.valueOf(s);
Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.
A long way to go :). I am not aware of methods to get rid of long for statements
ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
byte[] bArr = ss.getBytes();
for(Byte b : bArr) {
bList.add(b);
}
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
bArr[i] = bList.get(i);
}
Since there was no answer for hex string to single byte conversion, here is mine:
private static byte hexStringToByte(String data) {
return (byte) ((Character.digit(data.charAt(0), 16) << 4)
| Character.digit(data.charAt(1), 16));
}
Sample usage:
hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16
Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.
// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201
String source = "testString";
byte[] byteArray = source.getBytes(encoding);
You can foreach and do the same with all the strings in the array.
The simplest way (using Apache Common Codec):
byte[] bytes = Hex.decodeHex(str.toCharArray());
String str[] = {"aa", "55"};
byte b[] = new byte[str.length];
for (int i = 0; i < str.length; i++) {
b[i] = (byte) Integer.parseInt(str[i], 16);
}
Integer.parseInt(string, radix) converts a string into an integer, the radix paramter specifies the numeral system.
Use a radix of 16 if the string represents a hexadecimal number.
Use a radix of 2 if the string represents a binary number.
Use a radix of 10 (or omit the radix paramter) if the string represents a decimal number.
For further details check the Java docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)
Here, if you are converting string into byte[].There is a utility code :
String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
byte[] dataCopy = new byte[str.length] ;
int i=0;
for(String s:str ) {
dataCopy[i]=Byte.valueOf(s);
i++;
}
return dataCopy;

How to convert a string representation of unicode hex "0x20000" to the int code point 0x20000 in Java

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 "𠀀"

Categories

Resources