Java - Change int to ascii - java

Is there a way for java to convert int's to ascii symbols?

Do you want to convert ints to chars?:
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
Or do you want to convert ints to Strings?
int yourInt = 33;
String str = String.valueOf(yourInt);
Or what is it that you mean?

If you first convert the int to a char, you will have your ascii code.
For example:
int iAsciiValue = 9; // Currently just the number 9, but we want Tab character
// Put the tab character into a string
String strAsciiTab = Character.toString((char) iAsciiValue);

There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:
private static String toASCII(int value) {
int length = 4;
StringBuilder builder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
builder.append((char) ((value >> (8 * i)) & 0xFF));
}
return builder.toString();
}
For example, the ASCII text for "TEST" can be represented as the byte array:
byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
Then you could do the following:
int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.
char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));
Output:
Character: 1
Character: 49

In fact in the last answer
String strAsciiTab = Character.toString((char) iAsciiValue);
the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually
char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'

In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:
private static final char[] DIGITS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return DIGITS[digitValue];
}
Or, equivalently:
private static int ASCII_ZERO = 0x30;
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return ((char) (digitValue + ASCII_ZERO));
}

The most simple way is using type casting:
public char toChar(int c) {
return (char)c;
}

tl;dr
Use Character#toString, not char.
String result = Character.toString( yourAsciiNumber ) ;
Ex:
Character.toString( 97 ) // LATIN SMALL LETTER A
a
Character.toString( 128_567 ) // FACE WITH MEDICAL MASK
😷
char is legacy
The char type in Java is legacy, and is essentially broken. As a 16-bit value, char is incapable of representing most characters defined by Unicode.
This succeeds:
System.out.println( Character.toString( 128_567 )); // Unicode code points handle full-range of Unicode characters.
😷
This fails:
System.out.println( ( char ) 128_567 ); // `char` fails with most Unicode characters.
See code run live at IdeOne.com.
Code point
Use code point integer numbers to represent individual letters.
US-ASCII is a subset of Unicode. So, any US-ASCII number (0-127) is also a Unicode code point (0-1,114,111).
To change a code point number to a String object containing a single character, call Character#toString.
String x = Character.toString( 97 ) ;
a
See this code run live at IdeOne.com.

The most simple way is to get integer and just use the casting operator
Ex
int num = 33;
System.out.println((char) num); //Outputs 33
//if you want to find the integer value of character instead.
//Just do the reverse
char ch = '%';
System.out.println((int) ch);

Related

Get the Unicode from a Hexadecimal

I've been searching for a solution to my problem for days but can't get a spot-on answer when looking at previously answered questions/ blogs / tutorials etc. all over the internet.
My aim is to write a program which takes a decimal number as an input and then calculates the hexadecimal number and also prints the unicode-symbol of said hexadecimal number (\uXXXX).
My problem is I can't "convert" the hexadecimal number to unicode. (It has to be written in this format: \uXXXX)
Example:
Input:
122 (= Decimal)
Output:
Hexadecimal: 7A
Unicode: \u007A | Unicode Symbol: Latin small letter "z"
The only thing I've managed to do is print the unicode (\u007A), but I want the symbol ("z").
I thought if the unicode only has 4 numbers/letters, I would just need to "copy" the hexadecimal into the code and fill up the remaining places with 0's and it kinda worked, but as I said I need the symbol not the code. So I tried and tried, but I just couldn't get the symbol.
By my understanding, if you want the symbol you need to print it as a string.
But when trying it with a string I get the error "illegal unicode escape".
It's like you only can print pre-determined unicodes and not "random" ones generated on the spot in relation of your input.
I'm only a couple days into Java, so apologies if I have missed anything.
Thank you for reading.
My code:
int dec;
int quotient;
int rest;
int[]hex = new int[10];
char[]chars = new char[]{
'F',
'E',
'D',
'C',
'B',
'A'
};
String unicode;
// Input Number
System.out.println("Input decimal number:");
Scanner input = new Scanner(System.in);
dec = input.nextInt();
//
// "Converting to hexadecimal
quotient = dec / 16;
rest = dec % 16;
hex[0] = rest;
int j = 1;
while (quotient != 0) {
rest = quotient % 16;
quotient = quotient / 16;
hex[j] = rest;
j++;
}
//
/*if (j == 1) {
unicode = '\u000';
}
if (j == 2) {
unicode = '\u00';
}
if (j == 3) {
unicode = '\u0';
}*/
System.out.println("Your number: " + dec);
System.out.print("The corresponding Hexadecimal number: ");
for (int i = j - 1; i >= 0; i--) {
if (hex[i] > 9) {
if (j == 1) {
unicode = "\u000" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 2) {
unicode = "\u00" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 3) {
unicode = "\u0" + String.valueOf(chars[16 - hex[i] - 1]);
}
System.out.print(chars[16 - hex[i] - 1]);
} else {
if (j == 1) {
unicode = "\u000" + Character.valueOf[hex[i]);
}
if (j == 2) {
unicode = "\u00" + Character.valueOf(hex[i]);
}
if (j == 3) {
unicode = "\u0" + Character.valueOf(hex[i]);
}
System.out.print(hex[i]);
}
}
System.out.println();
System.out.print("Unicode: " + (unicode));
}
It's not an advanced code whatsoever, I wrote it exactly how I would calculate it on paper.
Dividing the number through 16 until I get a 0 and what remains while doing so is the hexadecimal equivalent.
So I put it in a while loop, since I would divide the number n-times until I got 0, the condition would be to repeat the division until the quotient equals zero.
While doing so the remains of each division would be the numbers/letters of my hexadecimal number, so I need them to be saved. I choose an integer array to do so. Rest (remains) = hex[j].
I also threw a variable in the called "j", so I would now how many times the division was repeated. So I could determine how long the hexadecimal is.
In the example it would 2 letters/numbers long (7A), so j = 2.
The variable would then be used to determine how many 0's I would need to fill up the unicode with.
If I have only 2 letters/numbers, it means there are 2 empty spots after \u, so we add two zeros, to get \u007A instead of \u7A.
Also the next if-command replaces any numbers higher than 9 with a character from the char array above. Basically just like you would do on paper.
I'm very sorry for this insanely long question.
U+007A is the 3 bytes int code pointer.
\u007A is the UTF-16 char.
A Unicode code pointer, symbol, sometimes is converted to two chars and then the hexadecimal numbers do not agree. Using code pointers hence is best. As UTF-16 is just an encoding scheme for two-bytes representation, where the surrogate pairs for 3 byte Unicode numbers do not contain / or such (high bit always 1).
int hex = 0x7A;
hex = Integer.parseUnsignedInt("007A", 16);
char ch = (char) hex;
String stringWith1CodePoint = new String(new int[] { hex }, 0, 1);
int[] codePoints = stringWith1CodePoint.codePoints().toArray();
String s = "𝄞"; // U+1D11E = "\uD834\uDD1E"
You can simply use System.out.printf or String.format to do what you want.
Example:
int decimal = 122;
System.out.printf("Hexadecimal: %X\n", decimal);
System.out.printf("Unicode: u%04X\n", decimal);
System.out.printf("Latin small letter: %c\n", (char)decimal);
Output:
Hexadecimal: 7A
Unicode: u007A
Latin small letter: z

Convert more than one char to an int in a string in Java

I understand how to convert a single char to an int, but how can I convert a String to chars, so I can convert the chars to ints? For example, for the string hello:
chars[1] = h => 104
chars[2] = e => 101
chars[3] = l => 108
chars[4] = l => 108
chars[5] = o => 111
The output should make it easy to convert five-letter Strings to five separate integers, each representing one character, then convert them back to char and print them as a single String again.
You can try like this:
String s = "hello";
char[] data = s.toCharArray(); // returns a length 5 char array ( 'h','e','l','l','o' )
Now you can call this function to convert it into int.
int charToInt(char []data,int start,int end) throws NumberFormatException
{
int result = 0;
for (int i = start; i < end; i++)
{
int digit = (int)data[i] - (int)'0';
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
Using getBytes(), you can get a byte[] containing an number representation of each letter in the String:
byte[] text = "hello".getBytes();
for(byte b : text) {
System.out.println(b);
}
This gives the same results as:
String text = "hello";
for(char c : text.toCharArray()) {
System.out.println((int) c);
}
This is the easiest way I can possibly think of to achieve this goal. To convert it back to String:
byte[] byteArray = "hello".getBytes();
String string = new String(byteArray);
You can pass the given string in the constructor parameter of StringBuilder class and use the codePointAt(int) method. It returns the ASCII value of character at the index specified.
There are other useful methods also in StringBuilder like codePointBefore(int) and appendCodePoint(int), which allow you to see the codepoint of the character before and append the character with the specified codepoint to the StringBuilder, respectively.
I assume here that the int value of each char should correspond to the Unicode code point of that character. If so, then the solution is trivial: you only need to type-cast between the char and int types. This is because in Java, a char is actually an Integral type just like an int. The char type can hold integer values that represent the code points of 16-bit Unicode characters ('\u0000' to '\uffff' or 0...65535).
The solution is to first, convert the String into a char[] using toCharArray. Then, simply cast each char into an int to get the Unicode code point value:
int capitalACodePoint = (int)'A';
Similarly, cast to char to get the value back:
char capitalA = (char) 65;
A runnable example:
String input = "hello";
List<Integer> codePoints = new ArrayList<>();
for (char c : input.toCharArray()) {
int codePoint = (int)c;
codePoints.add(codePoint);
System.out.println(String.format(
"char$ %d %s equals %d",
codePoints.size(), c, codePoint));
}
StringBuilder sb = new StringBuilder();
for (int codePoint : codePoints) {
sb.append((char) codePoint);
}
System.out.println(sb);
prints out
char$ 1 h equals 104
char$ 2 e equals 101
char$ 3 l equals 108
char$ 4 l equals 108
char$ 5 o equals 111
hello
This code also works with non-ASCII characters. Changing the input to
String input = "©†¿™";
prints out
char$ 1 © equals 169
char$ 2 † equals 8224
char$ 3 ¿ equals 191
char$ 4 ™ equals 8482
©†¿™

Creating a UUID from a string with no dashes

How would I create a java.util.UUID from a string with no dashes?
"5231b533ba17478798a3f2df37de2aD7" => #uuid "5231b533-ba17-4787-98a3-f2df37de2aD7"
tl;dr
java.util.UUID.fromString(
"5231b533ba17478798a3f2df37de2aD7"
.replaceFirst(
"(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5"
)
).toString()
5231b533-ba17-4787-98a3-f2df37de2ad7
Or parse each half of the hexadecimal string as long integer numbers, and pass to constructor of UUID.
UUID uuid = new UUID ( long1 , long2 ) ;
Bits, Not Text
A UUID is a 128-bit value. A UUID is not actually made up of letters and digits, it is made up of bits. You can think of it as describing a very, very large number.
We could display those bits as a one hundred and twenty eight 0 & 1 characters.
0111 0100 1101 0010 0101 0001 0101 0110
0110 0000 1110 0110 0100 0100 0100 1100
1010 0001 0111 0111 1010 1001 0110 1110
0110 0111 1110 1100 1111 1100 0101 1111
Humans do not easily read bits, so for convenience we usually represent the 128-bit value as a hexadecimal string made up of letters and digits.
74d25156-60e6-444c-a177-a96e67ecfc5f
Such a hex string is not the UUID itself, only a human-friendly representation. The hyphens are added per the UUID spec as canonical formatting, but are optional.
74d2515660e6444ca177a96e67ecfc5f
By the way, the UUID spec clearly states that lowercase letters must be used when generating the hex string while uppercase should be tolerated as input. Unfortunately, many implementations violate that lowercase-generation rule, including those from Apple, Microsoft, and others. See my blog post.
The following refers to Java, not Clojure.
In Java 7 (and earlier), you may use the java.util.UUID class to instantiate a UUID based on a hex string with hyphens as input. Example:
java.util.UUID uuidFromHyphens = java.util.UUID.fromString("6f34f25e-0b0d-4426-8ece-a8b3f27f4b63");
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );
However, that UUID class fails with inputting a hex string without hyphens. This failure is unfortunate as the UUID spec does not require the hyphens in a hex string representation. This fails:
java.util.UUID uuidFromNoHyphens = java.util.UUID.fromString("6f34f25e0b0d44268ecea8b3f27f4b63");
Regex
One workaround is to format the hex string to add the canonical hyphens. Here's my attempt at using regex to format the hex string. Beware… This code works, but I'm no regex expert. You should make this code more robust, say checking that the length of the string is 32 characters before formatting and 36 after.
// -----| With Hyphens |----------------------
java.util.UUID uuidFromHyphens = java.util.UUID.fromString( "6f34f25e-0b0d-4426-8ece-a8b3f27f4b63" );
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );
System.out.println();
// -----| Without Hyphens |----------------------
String hexStringWithoutHyphens = "6f34f25e0b0d44268ecea8b3f27f4b63";
// Use regex to format the hex string by inserting hyphens in the canonical format: 8-4-4-4-12
String hexStringWithInsertedHyphens = hexStringWithoutHyphens.replaceFirst( "([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5" );
System.out.println( "hexStringWithInsertedHyphens: " + hexStringWithInsertedHyphens );
java.util.UUID myUuid = java.util.UUID.fromString( hexStringWithInsertedHyphens );
System.out.println( "myUuid: " + myUuid );
Posix Notation
You might find this alternative syntax more readable, using Posix notation within the regex where \\p{XDigit} takes the place of [0-9a-fA-F] (see Pattern doc):
String hexStringWithInsertedHyphens = hexStringWithoutHyphens.replaceFirst( "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" );
Complete example.
java.util.UUID uuid =
java.util.UUID.fromString (
"5231b533ba17478798a3f2df37de2aD7"
.replaceFirst (
"(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)",
"$1-$2-$3-$4-$5"
)
);
System.out.println ( "uuid.toString(): " + uuid );
uuid.toString(): 5231b533-ba17-4787-98a3-f2df37de2ad7
Clojure's #uuid tagged literal is a pass-through to java.util.UUID/fromString. And, fromString splits it by the "-" and converts it into two Long values. (The format for UUID is standardized to 8-4-4-4-12 hex digits, but the "-" are really only there for validation and visual identification.)
The straight forward solution is to reinsert the "-" and use java.util.UUID/fromString.
(defn uuid-from-string [data]
(java.util.UUID/fromString
(clojure.string/replace data
#"(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})"
"$1-$2-$3-$4-$5")))
If you want something without regular expressions, you can use a ByteBuffer and DatatypeConverter.
(defn uuid-from-string [data]
(let [buffer (java.nio.ByteBuffer/wrap
(javax.xml.bind.DatatypeConverter/parseHexBinary data))]
(java.util.UUID. (.getLong buffer) (.getLong buffer))))
Regexp solution is probably faster, but you can also look at that :)
String withoutDashes = "44e128a5-ac7a-4c9a-be4c-224b6bf81b20".replaceAll("-", "");
BigInteger bi1 = new BigInteger(withoutDashes.substring(0, 16), 16);
BigInteger bi2 = new BigInteger(withoutDashes.substring(16, 32), 16);
UUID uuid = new UUID(bi1.longValue(), bi2.longValue());
String withDashes = uuid.toString();
By the way, conversion from 16 binary bytes to uuid
InputStream is = ..binarty input..;
byte[] bytes = IOUtils.toByteArray(is);
ByteBuffer bb = ByteBuffer.wrap(bytes);
UUID uuidWithDashesObj = new UUID(bb.getLong(), bb.getLong());
String uuidWithDashes = uuidWithDashesObj.toString();
You could do a goofy regular expression replacement:
String digits = "5231b533ba17478798a3f2df37de2aD7";
String uuid = digits.replaceAll(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
System.out.println(uuid); // => 5231b533-ba17-4787-98a3-f2df37de2aD7
A much (~ 900%) faster solution compared to using regexps and string manipulation is to just parse the hex string into 2 longs and create the UUID instance from those:
(defn uuid-from-string
"Converts a 32digit hex string into java.util.UUID"
[hex]
(java.util.UUID.
(Long/parseUnsignedLong (subs hex 0 16) 16)
(Long/parseUnsignedLong (subs hex 16) 16)))
public static String addUUIDDashes(String idNoDashes) {
StringBuffer idBuff = new StringBuffer(idNoDashes);
idBuff.insert(20, '-');
idBuff.insert(16, '-');
idBuff.insert(12, '-');
idBuff.insert(8, '-');
return idBuff.toString();
}
Maybe someone else can comment on the computational efficiency of this approach. (It wasn't a concern for my application.)
Optimized version of #maerics 's answer:
String[] digitsList= {
"daa70a7ffa904841bf9a81a67bdfdb45",
"529737c950e6428f80c0bac104668b54",
"5673c26e2e8f4c129906c74ec634b807",
"dd5a5ee3a3c44e4fb53d2e947eceeda5",
"faacc25d264d4e9498ade7a994dc612e",
"9a1d322dc70349c996dc1d5b76b44a0a",
"5fcfa683af5148a99c1bd900f57ea69c",
"fd9eae8272394dfd8fd42d2bc2933579",
"4b14d571dd4a4c9690796da318fc0c3a",
"d0c88286f24147f4a5d38e6198ee2d18"
};
//Use compiled pattern to improve performance of bulk operations
Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})");
for (int i = 0; i < digitsList.length; i++)
{
String uuid = pattern.matcher(digitsList[i]).replaceAll("$1-$2-$3-$4-$5");
System.out.println(uuid);
}
Another solution would be something similar to Pawel's solution but without creating new Strings and only solving the questions problem. If perfomance is a concern, avoid regex/split/replaceAll and UUID.fromString like the plague.
String hyphenlessUuid = in.nextString();
BigInteger bigInteger = new BigInteger(hyphenlessUuid, 16);
new UUID(bigInteger.shiftRight(64).longValue(), bigInteger.longValue());
I believe the following is the fastest in terms of performance. It is even slightly faster than Long.parseUnsignedLong version . It is slightly altered code that comes from java-uuid-generator.
public static UUID from32(
String id) {
if (id == null) {
throw new NullPointerException();
}
if (id.length() != 32) {
throw new NumberFormatException("UUID has to be 32 char with no hyphens");
}
long lo, hi;
lo = hi = 0;
for (int i = 0, j = 0; i < 32; ++j) {
int curr;
char c = id.charAt(i);
if (c >= '0' && c <= '9') {
curr = (c - '0');
}
else if (c >= 'a' && c <= 'f') {
curr = (c - 'a' + 10);
}
else if (c >= 'A' && c <= 'F') {
curr = (c - 'A' + 10);
}
else {
throw new NumberFormatException(
"Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
}
curr = (curr << 4);
c = id.charAt(++i);
if (c >= '0' && c <= '9') {
curr |= (c - '0');
}
else if (c >= 'a' && c <= 'f') {
curr |= (c - 'a' + 10);
}
else if (c >= 'A' && c <= 'F') {
curr |= (c - 'A' + 10);
}
else {
throw new NumberFormatException(
"Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
}
if (j < 8) {
hi = (hi << 8) | curr;
}
else {
lo = (lo << 8) | curr;
}
++i;
}
return new UUID(hi, lo);
}
Here is an example that is faster because it doesn't use regexp.
public class Example1 {
/**
* Get a UUID from a 32 char hexadecimal.
*
* #param string a hexadecimal string
* #return a UUID
*/
public static UUID toUuid(String string) {
if (string == null || string.length() != 32) {
throw new IllegalArgumentException("invalid input string!");
}
char[] input = string.toCharArray();
char[] output = new char[36];
System.arraycopy(input, 0, output, 0, 8);
System.arraycopy(input, 8, output, 9, 4);
System.arraycopy(input, 12, output, 14, 4);
System.arraycopy(input, 16, output, 19, 4);
System.arraycopy(input, 20, output, 24, 12);
output[8] = '-';
output[13] = '-';
output[18] = '-';
output[23] = '-';
return UUID.fromString(output)
}
public static void main(String[] args) {
UUID uuid = toUuid("daa70a7ffa904841bf9a81a67bdfdb45");
}
}
There's a codec in uuid-creator that can do it more efficiently: Base16Codec. Example:
// Parses base16 strings with 32 chars (case insensitive)
UuidCodec<String> codec = new Base16Codec();
UUID uuid = codec.decode("0123456789AB4DEFA123456789ABCDEF");

Binary Representation to a new byte

I'm trying to create a new byte knowing a certain amount of bits
char prostie1 = theRepChars[j-3];
char prostie2 = theRepChars[j-2];
char prostie3 = theRepChars[j-1];
char prostie4 = theRepChars[j];
String prostiaMare = prostie4 + prostie3 + prostie2 + prostie1 + "";
Byte theChar = new Byte(prostiaMare);
When i do this I get a NumberFormatException value 196.
I have no idea what might be my problem
--EDIT--
Ok I think I might have to give some more details since I wasn't very clear. I'm trying to do an Uuencode algorithm and by following the logic of the algorithm I should stop my byte having a value bigger than 194. Here is a bunch of my code.
if(my_chars.length % 3 == 0)
{
for(int x = 0; x < my_chars.length; x++)
{
if((x+1) % 3 == 0)
{
char first = my_chars[x-2];
char second = my_chars[x-1];
char third = my_chars[x];
int n = (((first << 8) | second) << 8) | third;
String theRep = Integer.toBinaryString(n);
while(theRep.length() < 24 - 1)
{
theRep = 0 + theRep;
}
//0 padded theRep
for(int j = 0; j < theRepChars.length; j++)
{
if((j+1) % 4 == 0)
{
char prostie1 = theRepChars[j-3];
char prostie2 = theRepChars[j-2];
char prostie3 = theRepChars[j-1];
char prostie4 = theRepChars[j];
String prostiaMare = prostie4 + prostie3 + prostie2 + prostie1 + "";
System.out.println(prostiaMare);
}
}
}
}
}
And trying to create a new byte with the value that prostiaMare has gives me the numberFormatException. I'm not sure if I have not followed the algorithm right ( http://www.herongyang.com/encoding/UUEncode-Algorithm.html )
196 is outside the range of byte, a signed value. Bytes can range from -128 to 127.
I'm not sure why you're casting to String. If you just want a byte with bits equivalent those of the sum of the four chars, cast directly to byte:
(byte) (prostie4 + prostie3 + prostie2 + prostie1)
If you intended to construct a String from the four chars, you are not currently doing that. Use:
"" + prostie4 + prostie3 + prostie2 + prostie1
and, if the result is in the range of a byte, you can create a byte as you have been.
Bytes are signed in Java. Which means a byte, which is 8 bits long, has a minimum value of -2^7 (-128) and a max value of 2^7 - 1 (127). Java has no unsigned primitive types apart from char (unsigned, 16bit).
Therefore 196 is unparseable --> NumberFormatException.
You don't have much to work around this except to read into a larger type and do & 0xff to obtain the byte:
final int i = Integer.parseInt(theString);
final byte b = (byte) (i & 0xff);
Or do yourself a favour and use Guava, which has UnsignedBytes:
final byte b = UnsignedBytes.parseUnsignedByte(theString);
But it appears that you want to do comparisons anyway; so just use a larger type than byte. And no, this won't waste memory: don't forget about alignment.
As mentioned in the docs
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first - character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
The value represented by the string is not a value of type byte.
In your case its the last case since 196 cant be represented as byte..The valid range is -128 to 127

Optimal code in Java to convert Integer value into Hexadecimal

I need to convert integer value into hexadecimal.
I have done with some logical, but I want the optimized solutions.
EDIT : Sorry I forgot to post that I am not allowed to use any in-built functions.
Easy:
String hex = Integer.toHexString(int);
Basically what this does is creating a new string, and then calling a method from the Integer class called toHexString which needs an int arg.
So pass the int you wanna change into this method and you'll get a String with the hexadecimal version of your int back.
You can put hexadecimal values in int types, but you cannot convert from int type to another int type, as far as i know, when you are doing hexadecimal conversions.
Remember that the value you get back is a String, so you cannot modify the value, otherwise you'll get an number format exception.
Assuming you don't want to use the built in toHexString for some reason, here's one pretty efficient way to do it:
public static char toHexChar(int i) {
i&=15;
return (i<10)? (char)(i+48) : (char)(i+55);
}
public static String toHexString(int n) {
char[] chars=new char[8];
for (int i=0; i<8; i++) {
chars[7-i]=toHexChar(n);
n>>=4;
};
return new String(chars);
}
Well then have a look at the implementation of Integer.toHexString(int). The following code is extracted from the Integer class in the java standard library.
public class Test {
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f'
};
private static String intAsHex(int i) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << 4;
int mask = radix - 1;
do {
buf[--charPos] = digits[i & mask];
i >>>= 4;
} while (i != 0);
return new String(buf, charPos, (32 - charPos));
}
public static void main(String... args) {
System.out.println(intAsHex(77));
}
}
Output: 4d
Check this
public class IntToHexa {
public static void main(java.lang.String args[]){
/*
* Here we need an integer to convert.
* [1]You can pass as command line argument
* [2]You can get as input from console
* [3]Take a constant. Here I'm taking a constant
*/
int intToConvert = 450;
java.lang.StringBuilder convertedHexa = new java.lang.StringBuilder("");
while (intToConvert > 15){
/*
* If the reminder is less than 10, add the remainder. else get the equivalent hexa code
* Here I'm getting the character code and adding the charater to the hexa string.
* For that I'm getting the difference between the reminder and 10.
* For example, if the reminder is 13, the reminder will be 3.
* Then add that difference to 65. In this example, it will become 68.
* Finally, get the quivalent char code of the result number. Here it will be D.
* Same for number, I'm adding it to 48
*/
convertedHexa.append(intToConvert % 16 < 10 ? ((char)(48 + (intToConvert % 16))) : ((char)(65 + (intToConvert % 16 - 10))));
intToConvert /= 16;
}
convertedHexa.append(intToConvert % 16 < 10 ? ((char)(48 + (intToConvert % 16))) : ((char)(65 + (intToConvert % 16 - 10))));
java.lang.System.out.println(convertedHexa.reverse());
}
}

Categories

Resources