Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String vs byte array representation

  1. I would like to know which representation of a String (normal String or byte-array) would require more memory to be stored?

  2. A byte-array representation is available to me in my code. Should I convert this to a String before transferring it over the network (in response to an AJAX call)?

like image 829
Sabaat Ahmad Avatar asked Nov 27 '15 12:11

Sabaat Ahmad


People also ask

What is the difference between byte array and string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

How is a byte array represented?

In . NET, a byte is basically a number from 0 to 255 (the numbers that can be represented by eight bits). So, a byte array is just an array of the numbers 0 - 255. At a lower level, an array is a contiguous block of memory, and a byte array is just a representation of that memory in 8-bit chunks.

How do you convert a byte array into a string?

// Code to convert byte arr to str: byte[] by_original = {0,1,-2,3,-4,-5,6}; String str1 = new String(by_original); System. out. println("str1 >> "+str1); // Code to convert str to byte arr: byte[] by_new = str1. getBytes(); for(int i=0;i<by_new.

Can byte array be stored in a string?

For text or character data, we use new String(bytes, StandardCharsets. UTF_8) to convert the byte[] to a String directly. However, for cases that byte[] is holding the binary data like the image or other non-text data, the best practice is to convert the byte[] into a Base64 encoded string.


1 Answers

1 => see: What is the Java's internal represention for String? Modified UTF-8? UTF-16?

2 => multiple options if it's short, simply transfer a string if it's ascii, otherwise, convert it :

String serial= DatatypeConverter.printBase64Binary(bytes)

and you can use GET

decoding is possible with java, php, ...

if it's big, use POST, and binary (or native).

like image 132
guillaume girod-vitouchkina Avatar answered Oct 05 '22 16:10

guillaume girod-vitouchkina