cbarber 115 posts since
Sep 27, 2007
6.
Re: How to convert String To Byte[]? Sep 30, 2008 9:04 AM
To convert a String (or, more generally, a StringInterface) to a ByteVec (aka {FastArray-of byte}) or ByteArray (aka {Array-of byte}) you will probably want to specify the character encoding you want to use. You can then use a TranscodingTextOutputStream to encode the characters and write them into a ByteArray through a ByteArrayOutputStream:
{define-proc {string-to-bytes string:StringInterface}:ByteArray
def bytes = {ByteArray}
{with-open-streams
out = {TranscodingTextOutputStream
{ByteArrayOutputStream bytes},
CharEncoding.utf8
}
do
{out.write-one-string string}
}
{return bytes}
}
If you know the size of the byte vec you need you can just use the built-in 'encode-characters' function to do this. If you don't mind the vector having wasted space in it you can write:
def bytes = {ByteVec max-size = string.size * char-encoding.transcoding-max-expansion-factor}
{encode-characters string, bytes, char-encoding}
Friedger's trick will work but is a little slow and does not specify the character encoding -- I think it will use UTF8, but I am not sure.
(I haven't tested any of this code, but I think it is correct.)