2

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.

3
  • 2
    Why don't you show us what you have? Commented Jan 22, 2015 at 14:03
  • 2
    Do you know the maximum and minimum values you will have to deal with? Commented Jan 22, 2015 at 14:04
  • 1
    If you need only four bytes, Int32 is fine, too. Commented Jan 22, 2015 at 14:58

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And Array.Reverse since it seems big-endian output is desired.
Where does this generate the fixed length array (I want to convert this to a fixed length hex byte array)?
@ChrFin This gives OP a variable-size array which he is free to extend. The important thing is that this approach would not truncate his data or throw an exception, no matter how many decimal digits is supplied.
Thanks @dasblinkenlight nice two-line answer - and thanks for demo!
4

You can use Linq:

  String source = "12345678";

  // "BC614E"
  String result = String.Concat(BigInteger
    .Parse(source)
    .ToByteArray()
    .Reverse()
    .SkipWhile(item => item == 0)
    .Select(item => item.ToString("X2")));

In case you want Byte[] it'll be

   // [0xBC, 0x61, 0x4E]
   Byte[] result = BigInteger
     .Parse(source)
     .ToByteArray()
     .Reverse()
     .SkipWhile(item => item == 0)
     .ToArray();

Comments

3

To convert the string to bytes you can use BitConverter.GetBytes:

var byteArray = BitConverter.GetBytes(Int32.Parse(decString)).Reverse().ToArray();

Use the appropriate type instead of Int32 if the string is not allways an 32 bit integer.
Then you could check the lenght and add padding bytes if needed:

if (byteArray.Length < 5)
{
    var newArray = new byte[5];
    Array.Copy(byteArray, 0, newArray, 5 - byteArray.Length, byteArray.Length);
    byteArray = newArray;
}

3 Comments

Assuming the decimal string represents a value that fits in a 32-bit int.
Thanks - that's certainly an improvement on my attempt! I'll give it a short while before accepting as best answer - as you never know ;-)
Can skip 3 bytes to give the same result as the OP: var result = BitConverter.GetBytes(ulong.Parse(decString)).Reverse().Skip(3).ToArray();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.