wildfireheart
wildfireheart

Reputation: 383

Haxe - hexadecimal string to haxe.io.Bytes

I am storing binary blob in SQLite, so with SELECT query I get hexadecimal string. Is there a simple way in haxe for converting this string of hex numbers to haxe.io.Bytes? (the reverse operation of Bytes toHex() function)

Upvotes: 2

Views: 2257

Answers (2)

Jonas Malaco
Jonas Malaco

Reputation: 1557

You can use BaseCode, and I'm not sure of an easier/one-liner way in the std lib.

import haxe.io.Bytes;
import haxe.crypto.BaseCode;

class Main {

    static function main() {
        var hex = "26fB0d";
        var bytes = decode(hex);
        trace(bytes.toHex());
    }

    static function decode(str:String) {
        var base = Bytes.ofString("0123456789abcdef");
        // not using `decode` or `decodeString` because the result may contain \0
        // and that is not accepted in strings on all targets
        return new BaseCode(base).decodeBytes(Bytes.ofString(str.toLowerCase()));
    }

}

Upvotes: 3

wildfireheart
wildfireheart

Reputation: 383

I come up with something like this:

public static function toBytes(hex:String):BytesData{

    var output = new haxe.io.BytesOutput();
    var len = Std.int(hex.length/2);

    for (i in 0...len){
        var byte:UInt = Std.parseInt(("0x" + hex.substr(i*2, 2)));
        output.writeByte(byte);
    }

    return output.getBytes().getData();
}

The answer from @jonasmalacofilho also works, probably better, I have yet to check, which is faster and if my solution is reliable.

Upvotes: 1

Related Questions