user3048644
user3048644

Reputation: 93

Format String as an hex value and append it in char array

I have the following code.

String test1 = "10";
String result = String.format("%02X", test1);
char buffer[] = {result.charAt(0),0x01,0x00,0x01,0x00,0x20};
byte[] bufferbyte = new String(buffer).getBytes();
for (byte b : bufferbyte){
  System.out.format("0X%x ", b);
}

Actually the string variable "test1" contains the decimal value. By this i mean to say that user can input 1 -256 integer digits and it is stored in "test1". I have placed 10 as the example . i need to append its hex value (0A) in char array, "buffer" at its first position and display it as an byte array containing hex value.

The above code is showing error as

"Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String"

Upvotes: 0

Views: 2049

Answers (2)

user177800
user177800

Reputation:

public class SSCCE
{
    public static void main(final String[] args)
    {
        final String ten = "10";
        final Integer i = Integer.parseInt(ten);
        System.out.format("%02X", i);
    }
}

ouputs 0A

You are trying to format a String you need to format the Integer representation.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

    String result = String.format("%02X", Integer.parseInt(test1));

Upvotes: 1

Related Questions