I have a integer:
int octalValue = 103
I want to convert this to text in Java. How can I do this?
The expected output would be 'C'.
Octal literals need to be prefixed with a 0:
int octalValue = 0103; //89
You can then convert it to the corresponding ASCII code:
char c = (char) octalValue; //C
This did it for me:
int octalValue = 123;
String abc = Integer.toString(octalValue);
char abcChar = (char) Integer.parseInt(abc, 8);
Better solutions might be out there.
Related
I have a String containing an ASCII digit character. I'd like to convert it to its ASCII-code as an int, so the charAt-method does not work directly here.
E.g. I have String number = "4";, how do I get its ASCII code (52) into an int?
You need the typecast the character to integer.
String name = "a";
char character = name.charAt(0);
int ascii = (int) character;
I'm looking for a straightforward answer and can't seem to find one.
I'm just trying to see if the following is valid. I want to take the integer 7 and turn it into the character '7'. Is this allowed:
int digit = 7;
char code = (char) digit;
Thank you in advance for your help!
This conversion is allowed, but the result won't be what you expect, because char 7 is the bell character whereas '7' is 55 (0x37). Because the numeric characters are in order, starting with '0' at 48 (0x30), just add '0', then cast the result as a char.
char code = (char) (digit + '0');
You may also take a look at the Unicode characters, of which the printable ASCII characters are the same codes.
'7' is Unicode code point U+0037.
Since it is a code point in the Basic Multiligual Plane, and since char is a UTF-16 code unit and that there is a one-to-one mapping between Unicode code points in this plane and UTF-16 code units, you can rely on this:
(char) ('0' + digit)
Do NOT think of '7' as ASCII 55 because that prevents a good understanding of char... For more details, see here.
Nope. The char '7' can be retrieved from int 7 in these ways:
int digit = 7;
char code = Integer.toString(digit).charAt(0);
code = Character.forDigit(digit, 10);
If digit is between 0 and 9:
int digit = 7;
char code = (char)(((int)'0')+digit);
I looked for this about an hour now, but couldn't get any advise specific to my problem. What I'd like to do is take a string of 0's and 1's and manipulate a char that it fits the given String pattern. For example:
char c = 'b'
String s = "00000000 01100001";
Now I'd like to manipulate the bits in c, so that they match the bit pattern specified in s. As result c would be printed as 'a' (if I'm not completely wrong about it). Any help appreciated!
You can do
char a = (char) Integer.parseInt("0000000001100001", 2);
To do the conversion from binary string to Integer, use parseInt with the 2nd argument as 2.
int temp = Integer.parseInt("01100001", 2);
You can modify with binary operators (&,|,^), but if what you really want is to just assign a variable, you can do it with casts.
char c = 'c';
System.out.println((char)(c&temp));
System.out.println((char)temp);
How about:
String s = "00000000 01100001";
String[] w = s.split(" ");
char c = (char)(Integer.parseInt(w[0], 2) * 256 + Integer.parseInt(w[1], 2));
This allows for the leading zeroes of each byte to be omitted. If you know they're there, you can just replace the space out of the string and use a single parseInt() call:
char c = (char)Integer.parseInt(s.replace(" ", ""), 2);
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;
String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
System.out.println(l);
how would i get the F and L variables converted to uppercase.
You can use Character#toUpperCase() for this.
char fUpper = Character.toUpperCase(f);
char lUpper = Character.toUpperCase(l);
It has however some limitations since the world is aware of many more characters than can ever fit in 16bit char range. See also the following excerpt of the javadoc:
Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the toUpperCase(int) method.
Instead of using existing utilities, you may try below conversion using boolean operation:
To upper case:
char upperChar = 'l' & 0x5f
To lower case:
char lowerChar = 'L' ^ 0x20
How it works:
Binary, hex and decimal table:
------------------------------------------
| Binary | Hexadecimal | Decimal |
-----------------------------------------
| 1011111 | 0x5f | 95 |
------------------------------------------
| 100000 | 0x20 | 32 |
------------------------------------------
Let's take an example of small l to L conversion:
The binary AND operation: (l & 0x5f)
l character has ASCII 108 and 01101100 is binary represenation.
1101100
& 1011111
-----------
1001100 = 76 in decimal which is **ASCII** code of L
Similarly the L to l conversion:
The binary XOR operation: (L ^ 0x20)
1001100
^ 0100000
-----------
1101100 = 108 in decimal which is **ASCII** code of l
Have a look at the java.lang.Character class, it provides a lot of useful methods to convert or test chars.
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
Since you know the chars are lower case, you can subtract the according ASCII value to make them uppercase:
char a = 'a';
a -= 32;
System.out.println("a is " + a); //a is A
Here is an ASCII table for reference
System.out.println(first.substring(0,1).toUpperCase());
System.out.println(last.substring(0,1).toUpperCase());
If you are including the apache commons lang jar in your project than the easiest solution would be to do:
WordUtils.capitalize(Name)
takes care of all the dirty work for you.
See the javadoc here
Alternatively, you also have a capitalizeFully(String) method which also lower cases the rest of the characters.
You can apply the .toUpperCase() directly on String variables or as an attribute to text fields. Ex: -
String str;
TextView txt;
str.toUpperCase();// will change it to all upper case OR
txt.append(str.toUpperCase());
txt.setText(str.toUpperCase());
Lets assume you have a variable you want split
String name = "Your name variable";
char nameChar = Character.toUpperCase(name.charAt(0));
I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.
Can be done through StringBuffer:
public static String toFirstLastCharUpperAll(String string){
StringBuffer sb=new StringBuffer(string);
for(int i=0;i<sb.length();i++)
if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
|| i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
return sb.toString();
}
The easiest solution for your case - change the first line, let it do just the opposite thing:
String lower = Name.toUpperCase ();
Of course, it's worth to change its name too.