[java] How to convert a Java String to an ASCII byte array?

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

This question is related to java arrays string ascii bytearray

The answer is


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

Example:

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

(Before Java 7: byte[] b = s.getBytes("US-ASCII");)


String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");

I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.

byte[] byteArray;                                                  
     byteArray= json.getBytes(StandardCharsets.US_ASCII);
    String encoded=Base64.encodeBytes(byteArray);
    userLogin(encoded);

Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html


If you happen to need this in Android and want to make it work with anything older than FroYo, you can also use EncodingUtils.getAsciiBytes():

byte[] bytes = EncodingUtils.getAsciiBytes("ASCII Text");

Try this:

/**
 * @(#)demo1.java
 *
 *
 * @author 
 * @version 1.00 2012/8/30
 */

import java.util.*;

public class demo1 
{
    Scanner s=new Scanner(System.in);

    String str;
    int key;

    void getdata()
    {
        System.out.println ("plase enter a string");
        str=s.next();
        System.out.println ("plase enter a key");
        key=s.nextInt();
    }

    void display()
    {
        char a;
        int j;
        for ( int i = 0; i < str.length(); ++i )
        {

            char c = str.charAt( i );
            j = (int) c + key;
            a= (char) j;

            System.out.print(a);  
        }

        public static void main(String[] args)
        {
            demo1 obj=new demo1();
            obj.getdata();
            obj.display();
        }
    }
}

If you are a 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.


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 values.

   String test = "ABCD";

   for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
   }

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

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to ascii

Detect whether a Python string is a number or a letter Is there any ASCII character for <br>? UnicodeEncodeError: 'ascii' codec can't encode character at special name Replace non-ASCII characters with a single space Convert ascii value to char What's the difference between ASCII and Unicode? Invisible characters - ASCII How To Convert A Number To an ASCII Character? Convert ascii char[] to hexadecimal char[] in C Convert character to ASCII numeric value in java

Examples related to bytearray

How to create bitmap from byte array? Put byte array to JSON and vice versa Byte Array to Hex String Java ByteBuffer to String Fastest way to convert Image to Byte array How to store a byte array in Javascript Conversion from byte array to base64 and back How do I print bytes as hexadecimal? How to convert image into byte array and byte array to base64 String in android? How to convert a byte array to a hex string in Java?