Big Integer and Hex Strings in java - 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.

Related

Extracting a char from a string

I need to extract a char from a preset string. I know the method string.charAt(), I use it but it crash my program. The context that I use is the following :
private String values = "0123456789ABCDEFG";
//Converts a 10 base number to a q base
private String t2q(String number, String base) {
String a = Double.toString((int)(Double.parseDouble(number) / Double.parseDouble(base)));
String b = Double.toString((int)(Double.parseDouble(number) % Double.parseDouble(base)));
StringBuilder converted = new StringBuilder(a + b);
if (!check_base(converted.toString(), base)) {
return t2q(a, base) + values.charAt(Integer.parseInt(b));
}
char ab = values.charAt(Integer.parseInt(a));
char ba = values.charAt(Integer.parseInt(b));
return "" + ab + ba;
}
At the beginning i was thinking that my program crash because a is in a Double format e.g 1.0 so i use a function that transforms 1.0 in 1 but nothing, it still crashes. Also i tried with Character instead of char but it doesn't make a difference.
The Exception Error is "java.lang.NumberFormatException: Invalid int : "1.0"" for the example number = "11011" and base = 16 , so 11011 in base 16 is 1B.
You can't parse a String which represents a Double with Integer.parseInt().
This will not work:
Integer.parseInt("3.0");
This will work:
Integer.parseInt("3");
Use this instead:
new Double("3.0").intValue()
But consider following behavior:
new Double("2.5").intValue() will return 2.

Writing string to byte array in 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.

Concat the two first characters of string

I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?
You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring
What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.
String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);

Java - Construct a signed numeric String and convert it to an integer

Can I somehow prepend a minus sign to a numeric String and convert it into an int?
In example:
If I have 2 Strings :
String x="-";
String y="2";
how can i get them converted to an Int which value is -2?
You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.
Therefore this will print -2 the way you want it:
String x = "-";
String y = "2";
int i = Integer.parseInt(x + y);
System.out.println(i);
Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.
Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.
If you're trying to get a character code, use the following:
(int) "-".charAt(0);
charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

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;

Categories

Resources