reinhard.lee
reinhard.lee

Reputation: 503

Java String to byte conversion is different

All

I have a question for send byte array to Server.

The Each ID has Text Value.

private String ID = "0001";
byte STX = (byte)0x02;
byte A = (byte)0x41;
byte NUL = (byte)0x00;
byte ETX = (byte)0x03;
byte CR = (byte)0x0D;
byte LF = (byte)0x0A;
byte[] buffer = { STX, Byte.decode(ID), A, NUL, ETX, CR, LF };

I expected buffer values

buffer [02, 48, 48, 48, 49, 65, 00, 0D, 0A]

but buffer value has

buffer [02, 01, 65, 00, 0D, 0A]

How Can I Convert to "0001" to [48, 48, 48, 49], String to Decimal Conversion.

Upvotes: 4

Views: 3211

Answers (2)

Liu guanghua
Liu guanghua

Reputation: 991

import java.nio.ByteBuffer;
 ...

    ByteBuffer buffer2 = ByteBuffer.allocate(10);
    buffer2.put(STX);
    buffer2.put(ID.getBytes());
    buffer2.put(A);
    buffer2.put(NUL);
    buffer2.put(ETX);
    buffer2.put(CR);
    buffer2.put(LF);

    byte[] data = buffer2.array();
    buffer2.clear();

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279900

The method Byte#decode(String) returns a single Byte that is added as an element to you buffer array.

The String "0001" represents the octal value 0001 which is 1.

You won't be able to add multiple array elements with one variable in a { } initialization notation.

Instead, you can do the following

String ID = "0001";
byte STX = (byte) 0x02;
byte A = (byte) 0x41;
byte NUL = (byte) 0x00;
byte ETX = (byte) 0x03;
byte CR = (byte) 0x0D;
byte LF = (byte) 0x0A;
List<Byte> bytes = new ArrayList<Byte>();
bytes.add(STX);
for (char c : ID.toCharArray()) {
    bytes.add((byte)c); 
}
bytes.addAll(Arrays.asList(A, NUL, ETX, CR, LF));

Byte[] buffer = (Byte[]) bytes.toArray(new Byte[0]);
System.out.println(Arrays.toString(buffer));

prints

[2, 48, 48, 48, 49, 65, 0, 3, 13, 10]

Note that this solution might not work as you expect when the char value goes over the value range that byte can hold.

Upvotes: 2

Related Questions