Integers to Bit Array

  • Thread starter Thread starter amaca
  • Start date Start date
A

amaca

I need to pack two (or more) ints into a byte []. I know I can use
BitConverter to to convert one int into a byte [], but how do I do more -
and how do I get them out again?

byte [] ToByteArray(int a, int b)
{
return ???;
}

void FromByteArray(byte [] byteArray, out int a, out int b)
{
???
}

Thanks,

Andrew
 
amaca said:
I need to pack two (or more) ints into a byte []. I know I can use
BitConverter to to convert one int into a byte [], but how do I do more -
and how do I get them out again?

byte [] ToByteArray(int a, int b)
{
return ???;
}

void FromByteArray(byte [] byteArray, out int a, out int b)
{
???
}

Unfortunately the normal BitConverter doesn't help you as much as it
could in terms of putting them together.

I have a version of BitConverter in my miscellaneous utility library
which not only allows you to specify the endianness, but also has a
CopyBytes method (IIRC - something like that). It's like GetBytes, but
it lets you specify an existing byte array and the index at which to
copy the bytes.

FromByteArray is reasonable with the normal BitConverter though - just
use:
a = BitConverter.ToInt32(byteArray, 0);
b = BitConverter.ToInt32(byteArray, 4);

My library is available at
http://www.pobox.com/~skeet/csharp/miscutil

Jon
 
Many thanks - just what I need. As is often the case, the problem was indeed
'something that doesn't exist in the framework but {we/I} think it should'.

Andrew
 
Back
Top