www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - string to ubyte[]

reply berni <someone somewhere.com> writes:
I've got a function which takes two strings and should return 
them as a ubyte[] with additional zero bytes in between and 
around. This works:

    ubyte[] convert_string_pair(string first, string second)
    {
        auto b = new ubyte[](0);
        b ~= 0x00 ~ first ~ 0x00 ~ second ~ 0x00;
        return b;
    }
But I think it would be more elegant to do it in a single return statement, but unfortunately this does not work:
    ubyte[] convert_string_pair(string first, string second)
    {
        return 0x00 ~ first ~ 0x00 ~ second ~ 0x00;
    }
The reason is, that this expression creates a string and not a ubyte[]...
Aug 14 2019
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 14 August 2019 at 15:11:44 UTC, berni wrote:
 The reason is, that this expression creates a string and not a 
 ubyte[]...
it should be ok to just cast it in this case.
Aug 14 2019
prev sibling parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Wed, Aug 14, 2019 at 03:11:44PM +0000, berni via Digitalmars-d-learn wrote:
[...]
 but unfortunately this does not work:
 
    ubyte[] convert_string_pair(string first, string second)
    {
        return 0x00 ~ first ~ 0x00 ~ second ~ 0x00;
    }
The reason is, that this expression creates a string and not a ubyte[]...
Try: ubyte[] convert_string_pair(string first, string second) { return cast(ubyte[])(0x00 ~ first ~ 0x00 ~ second ~ 0x00); } T -- What did the alien say to Schubert? "Take me to your lieder."
Aug 14 2019