-4

i want to display the first 4 characters of my dummy data. How do i do that? I want as output :

outputvalue = $*
outputvalue = 22



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    byte[] outData = ("$*220000000000101SDFRGGHYB0").getBytes();
    ByteBuffer b = ByteBuffer.wrap(outData);
    System.out.println("The structure"+ b);
    outputvalue1 = $*
    outputvalue2 = 22



}
  • The problem here: what kind of strings are you talking about? You understand that Characters in Java represent Unicode. There is no guarantee that your "first 2 chars" fit into 4 bytes?! – GhostCat May 16 '19 at 11:34
  • Are you wanting the output "$*22"? – Steve Smith May 16 '19 at 11:34
  • no i want 1 output value $* and 1 output value 22 – user3761485 May 16 '19 at 11:35
  • And why do you expect the `short` (16-bit integer) you created with the first two bytes of your char array to print as `"$*"`? You deliberately turned it into an integer, when you want to see a string. Did you actually want to use a `CharBuffer`, have it produce a `String`, and then print two different `String.substring()`s, or similar? – Useless May 16 '19 at 12:09

1 Answers1

0
byte[] outData = "$*220000000000101SDFRGGHYB0".getBytes("UTF-8");
ByteBuffer b = ByteBuffer.wrap(outData);

byte[] outputValue1 = new byte[2];
b.get(outputValue1);

byte[] outputValue2 = new byte[2];
b.get(outputValue2);

String outputString1 = new String(outputValue1, "UTF-8");
String outputString2 = new String(outputValue2, "UTF-8");
int outputNum2 = Integer.parseInt(outputString2);

String is always in Unicode, and binary data (byte[]) as text have some encoding, charset. This must be mentioned when converting between String/Reader/Writer and byte[]/InputStream/OutputStream

ByteBuffer allows positioned, random access reading and writing. The above uses linear reading.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138