1

I would like to write binary data to a file for an ancillary hash table operation and then read it back using stream.rawRead(). How would I go about converting a string to binary in D. I would prefer not to use any third party libraries if I can.

3 Answers 3

4

The built in module std.utf has methods to convert to and from the utf encodings (with utf8 being compatible with ascii).

If you want to use raw read you should write the length of the string first so when reading you know how many bytes the string is.

Sign up to request clarification or add additional context in comments.

1 Comment

That is what I was looking for to get me started. Thank you
3

Side note - if your strings are ASCII, it is pretty much straightforward:

// following will not work: // ubyte[] stringBytes = cast(ubyte[]) "Добар дан!".dup; ubyte[] stringBytes = cast(ubyte[]) "Hello world".dup; writeln(stringBytes); char[] charr = cast(char[]) stringBytes; writeln(charr); string str = to!string(charr); writeln(str); 

Output:

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] Hello world Hello world 

As Ratched pointed out, you will need some sort of unicode conversion...

1 Comment

Wow, both recommendations have been spot on!!! Thank you and ratchet freak tremendously.
0

Another option is representation:

import std.stdio, std.string; void main() { auto s = "March"; auto a = s.representation; a.writeln; // [77, 97, 114, 99, 104] } 

https://dlang.org/library/std/string/representation.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.