Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct string from byte array in D

I have array of bytes which is defined as pointer + size:

  size_t size;   // size in bytes
  void   *data;  // NOT zero-terminated string

How do I construct, preferably zero-copy, 'string' from it?

like image 319
Brazhnyk Yuriy Avatar asked Feb 17 '15 00:02

Brazhnyk Yuriy


People also ask

How do I print a byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.

Which method is used to convert a string to an array of bytes?

Using String. getBytes() The String class provides three overloaded getBytes methods to encode a String into a byte array: getBytes() – encodes using platform's default charset.

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


1 Answers

This assumes that data points to immutable memory:

string s = (cast(immutable(char)*)data)[0..size];

If it doesn't, a char[] would be more appropriate instead of a string, or you can make an immutable copy with .idup.

like image 182
Vladimir Panteleev Avatar answered Nov 28 '22 12:11

Vladimir Panteleev