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
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.
1 Comment
Coldstar
That is what I was looking for to get me started. Thank you
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
Coldstar
Wow, both recommendations have been spot on!!! Thank you and ratchet freak tremendously.
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] }