CopyPastehas never been so tasty!

Convert Byte Array to String and hex string in java

by anonymous

  • 0
  • 0
  • 0
63 views

Convert Byte Array to String and hex string in java

Byte Type:The byte type consists of 8 bit 2’s singed integer. It has a minimum value of -128 and a maximum value of 127. The byte data type is also useful for storing memory in larger arrays.Hex Type:Hexadecimal data types are integer types. They provide a suitable characters or numbers for integer values in the binary number system. Hexadecimal number system has 16 characters.Conversion of Byte array into String:In order To convert Byte array into String you have to make a class and then to convert byte [ ] array to String correctly we need to create a String object and assign the Byte array to it. For example String s = new String (bytes);Above object take the byte array as parameter and converts the array into string.Following is the sample code:

public class Main

 {

  public static void main(String[] args)

    {

        byte[] byteArray = new byte[] {98, 34, 56, 26, 68, 94};

        String number = new String (byteArray);

        System.out.println(number);

    }

}

Conversion of Byte Array into Hex String:  

 To convert Byte Array into hex String you have to make a class. Then you have to use getBytes method. Then you will use for loop to get data from byte array.String buffer is used to implement sequence of characters. It is also like String but it can be changed e.g. StringBuffer sb = new StringBuffer(b.length * 2);.

Following is the sample code:

public class Main { 

  public static void main(String arg[]) {

    byteArrayToHexString(("abc").getBytes());

  }

  public static String byteArrayToHexString(byte[] b) {

    StringBuffer sb = new StringBuffer(b.length * 2);

    for (int i = 0; i < b.length; i++) {

      int v = b[i] & 0xff;

      if (v < 16) {

        sb.append('0');

      }

      sb.append(Integer.toHexString(v));

    }

    return sb.toString().toUpperCase();

  }

 }

 This is a simple article that Convert Byte Array into String and hex string in java.

 

Add A Comment: