Convert string to ascii java

How to convert a Java String to an ASCII byte array?

Using the getBytes method, giving it the appropriate Charset (or Charset name).

String s = "Hello, there."; byte[] b = s.getBytes(StandardCharsets.US_ASCII); 

If more control is required (such as throwing an exception when a character outside the 7 bit US-ASCII is encountered) then CharsetDecoder can be used:

private static byte[] strictStringToBytes(String s, Charset charset) throws CharacterCodingException

Before Java 7 it is possible to use: byte[] b = s.getBytes(«US-ASCII»); . The enum StandardCharsets , the encoder as well as the specialized getBytes(Charset) methods have been introduced in Java 7.

This will convert unmappable characters like ‘\u00e0’ (à) into ‘?’. It would be nicer to have a method that converts that into ‘a’.

For people using Java 7 or later, use the class StandardCharsets which contains some constants for standard charsets. byte[] b = s.getBytes(StandardCharsets.US_ASCII);

If you are a guava user there is a handy Charsets class:

String s = "Hello, world!"; byte[] b = s.getBytes(Charsets.US_ASCII); 

Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII is of Charset type (not String ) so you avoid checked UnsupportedEncodingException thrown only from String.getBytes(String) , but not from String.getBytes(Charset) .

In Java 7 there is equivalent StandardCharsets class.

sadly, String.getBytes(Charset) was not added until API 9 🙁 So if you want to target Froyo and above, you can’t do that.

There is only one character wrong in the code you tried:

Charset characterSet = Charset.forName("US-ASCII"); String string = "Wazzup"; byte[] bytes = String.getBytes(characterSet); ^ 

Notice the upper case «String». This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:

byte[] bytes = string.getBytes(characterSet); 

if so , can you please tell me how could it be that an hebrew letter is taken 1 byte (ascii encoding) , it even doesnt exists in the ascii. and it is not using default encodung since i specified manually. i.stack.imgur.com/5WPD3.jpg

@RoyiNamir: This might be better posted as a new question, but the reason is that character is not encodable in US-ASCII and the getBytes(Charset) method is specified to replace characters that can not be encoded. With US-ASCII, this replacement char is the question mark, so your byte array contains one element with the ASCII value of ‘?’ (63).

The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like ? .

You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing ‘normalization’ defined for unicode), but those methods are far from complete.

Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII.

Источник

Convert String to ASCII Java

Convert String to ASCII Java | ASCII expands as American Standard Code For Information Interchange this is widely used to transfer the information or messages between the computers & it usually contains numerical, letters, and also other symbols. ASCII is a character encoding standard for electronic exchange. The ASCII values are case-sensitive hence it has different values for the character ‘a’ and the character ‘A’.

For Example:
ASCII value for ‘A’ = 65
ASCII value for ‘B’ = 66 and so on.
See more:- Java program to display ASCII value of a given character

To convert the string to its equivalent ASCII we have to get the ASCII value of each character. Example:-
String = “KnowProgram”;
ASCII = “751101111198011411110311497109”

String To ASCII Java using String.getBytes()

In Java, the String class contains the getBytes() method which encodes given String into a sequence of bytes using the named charset, storing the result into a new byte array. The below program demonstrate the String.getBytes() method.

import java.util.Arrays; public class Main < public static void main(String args[]) < try < String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; byte[] bytes = txt.getBytes("US-ASCII"); System.out.println("ASCII: " + Arrays.toString(bytes)); >catch (java.io.UnsupportedEncodingException e) < e.printStackTrace(); >> >

ASCII: [ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 ]

Using the getBytes() we can get the equivalent ASCII value of the given string by concatenating each byte value from the array. Let us see it through an example:-

import java.util.Arrays; public class Main < public static void main(String args[]) < try < String txt = "KnowProgram"; byte[] bytes = txt.getBytes("US-ASCII"); System.out.println("Bytes array: " + Arrays.toString(bytes)); StringBuilder sb = new StringBuilder(""); for (byte value : bytes) < sb.append(value); >String ascii = sb.toString(); System.out.println("ASCII: " + ascii); > catch (java.io.UnsupportedEncodingException e) < e.printStackTrace(); >> >

Bytes array: [75, 110, 111, 119, 80, 114, 111, 103, 114, 97, 109]ASCII: 751101111198011411110311497109

The same can be done without using the getBytes() method. In that case, we have to just convert char to int value and concatenate them. Below program shows it:-

String To ASCII Java without using String.getBytes()

public class Main < public static void main(String args[]) < String txt = "KnowProgram"; StringBuilder sb = new StringBuilder(""); for (int i = 0; i < txt.length(); i++) < sb.append((int) txt.charAt(i)); >String ascii = sb.toString(); System.out.println("ASCII: " + ascii); > >

Binary String To ASCII Java

In this code, we first convert binary to decimal and then set it to the respective ASCII.

public class Main < static int binToDec(String n) < String number = n; int dec = 0; int base = 1; int len = number.length(); for (int i = len - 1; i >= 0; i--) < if (number.charAt(i) == '1') dec += base; base = base * 2; >return dec; > static String stringtoASCII(String str) < int N = (str.length()); if (N % 8 != 0) < return "Not Possible!"; >String res = ""; for (int i = 0; i < N; i += 8) < int decimal_value = binToDec((str.substring(i, 8 + i))); res += decimal_value; >return res; > public static void main(String[] args) < String s = "0110000101100010"; System.out.print(stringtoASCII(s)); >>

Java Convert ASCII To String

Previously we have converted String to ASCII equivalent and binary string to ASCII equivalent. Now let us see its reverse operation. We will convert ASCII equivalent to string format. But before let us see a simple program to convert an ASCII value to a string:-

ASCII values of alphabets belong from 32 to 122. Hence we will get a digit from the ASCII equivalent and form the number. If the number belongs between the 32 to 122 range then we will convert them into characters. Let us see the example.

Program to Convert ASCII to String in Java

public class Main < public static void main(String[] args) < String ascii = "751101111198011411110311497109"; String string = asciiToSentence(ascii, ascii.length()); System.out.println("String: " + string); >public static String asciiToSentence(String ascii, int length) < int num = 0; StringBuilder sb = new StringBuilder(""); for (int i = 0; i < length; i++) < num = num * 10 + (ascii.charAt(i) - '0'); // If num is within the range if (num >= 32 && num > return sb.toString(); > >

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How to convert a java string to an ascii byte array?

Java provides several ways to convert a String to an ASCII byte array. Here are two methods you can use:

Method 1: Using the getBytes() method

  • Step 1 — Create a String variable and initialize it with the value you want to convert to an ASCII byte array.
String myString = "Hello World";

The getBytes() method returns a byte array containing the ASCII values of the characters in the String.

byte[] myByteArray = myString.getBytes();
for (byte b : myByteArray)  System.out.print(b + " "); >

Method 2: Using the CharsetEncoder class

  • Step 1 — Create a String variable and initialize it with the value you want to convert to an ASCII byte array.
String myString = "Hello World";
CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder();
  • Step 3 — Use the encode() method of the CharsetEncoder class to convert the String to a byte array

The encode() method returns a ByteBuffer containing the ASCII values of the characters in the String.

ByteBuffer byteBuffer = asciiEncoder.encode(CharBuffer.wrap(myString));
byte[] myByteArray = new byte[byteBuffer.remaining()]; byteBuffer.get(myByteArray);
for (byte b : myByteArray)  System.out.print(b + " "); >

Both these methods will give you a byte array containing the ASCII values of the characters in the string. The first method is simpler and easier to use, but the second method provides more flexibility and control over the encoding process. It’s important to note that ASCII only contains 128 characters, so if the String contains any characters outside of the ASCII range, they will be replaced with ‘?’ in the resulting byte array.

It’s also important to note that the byte array returned by these methods is not the same as the binary representation of the String. The byte array contains the ASCII values of the characters in the String, whereas the binary representation of the String would contain the Unicode encoding of the characters.

Another thing to keep in mind is that the getBytes() method uses the default character encoding of the platform where your code is running. This means that the resulting byte array may be different on different platforms or when running your code on a different version of Java. To ensure that the byte array is consistent across different platforms, you can use the getBytes(Charset) method and specify the character encoding you want to use.

Here’s an example of how to use the getBytes(Charset) method to convert a String to an ASCII byte array:

String myString = "Hello World"; byte[] myByteArray = myString.getBytes(StandardCharsets.US_ASCII); for (byte b : myByteArray)  System.out.print(b + " "); >

In this example, we used the StandardCharsets.US_ASCII constant to specify that we want to use the US-ASCII character encoding.

Conclusion

In conclusion, converting a Java String to an ASCII byte array is a simple task that can be achieved using the built-in methods provided by the Java String class. The getBytes() method and the CharsetEncoder class are two methods you can use to perform the conversion. The getBytes() method is simpler and easier to use, but the CharsetEncoder class provides more flexibility and control over the encoding process. However, it’s important to note that ASCII only contains 128 characters, so if the String contains any characters outside of the ASCII range, they will be replaced with ‘?’ in the resulting byte array. Also keep in mind that the getBytes() method uses the default character encoding of the platform where your code is running. To ensure that the byte array is consistent across different platforms, you can use the getBytes(Charset) method and specify the character encoding you want to use.

Источник

Читайте также:  Java awt color setcolor
Оцените статью