Search code examples
d

How do I convert a BigInt to a ubyte[]?


I have a long number I'd like to encode:

eg. 421400434911950871535

What I'd like to do is represent it in a variety of encodings, eg. Base64, ASCII85 or Base32.

In order to do this I think I probably need to get it into a ubyte[], based on the API of std.base64. I'm having trouble working out how to do it. I can get it to a hex string as follows:

import std.stdio;
import std.bigint;
import std.conv;

void main() {
    BigInt bignumber = ("421400434911950871535");

    string hexstr;

    bignumber.toString(delegate (foo){hexstr = to!string(foo); }, "%X");

    writeln(hexstr);

;}

Which gives me

"16_D81B16E0_91F31BEF".

What I'd like to do is get it into a ubyte[] that looks like this:

[16, D8, 1B, 16, E0, 91, F3, 1B, EF]

Is there simple way to do this?


Solution

  • Best answer so far, thanks to 'Anonymous' on the D forums:

    import std.conv: parse;
    import std.array: array;
    import std.range: chunks;
    import std.algorithm: map;
    
    auto hexstr = "16D81B16E091F31BEF";
    
    ubyte[] bytes = (hexstr.length % 2 ? "0" ~ hexstr : hexstr)
                    .chunks(2)
                    .map!(twoDigits => twoDigits.parse!ubyte(16))
                    .array();