Search code examples
c#hexarrays

How to convert decimal string value to hex byte array in C#?


I have an input string which is in decimal format:

var decString = "12345678"; // in hex this is 0xBC614E

and I want to convert this to a fixed length hex byte array:

byte hexBytes[] // = { 0x00, 0x00, 0xBC, 0x61, 0x4E }

I've come up with a few rather convoluted ways to do this but I suspect there is a neat two-liner! Any thoughts? Thanks

UPDATE:

OK I think I may have inadvertently added a level of complexity by having the example showing 5 bytes. Maximum is in fact 4 bytes (FF FF FF FF) = 4294967295. Int64 is fine.


Solution

  • If you have no particular limit to the size of your integer, you could use BigInteger to do this conversion:

    var b = BigInteger.Parse("12345678");
    var bb = b.ToByteArray();
    foreach (var s in bb) {
        Console.Write("{0:x} ", s);
    }
    

    This prints

    4e 61 bc 0
    

    If the order of bytes matters, you may need to reverse the array of bytes.

    Maximum is in fact 4 bytes (FF FF FF FF) = 4294967295

    You can use uint for that - like this:

    uint data = uint.Parse("12345678");
    byte[] bytes = new[] {
        (byte)((data>>24) & 0xFF)
    ,   (byte)((data>>16) & 0xFF)
    ,   (byte)((data>>8) & 0xFF)
    ,   (byte)((data>>0) & 0xFF)
    };
    

    Demo.