Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Integers to Bit Array

0 views
Skip to first unread message

amaca

unread,
Feb 20, 2006, 9:00:20 AM2/20/06
to

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


Jon Skeet [C# MVP]

unread,
Feb 20, 2006, 9:06:59 AM2/20/06
to

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

amaca

unread,
Feb 20, 2006, 9:24:15 AM2/20/06
to
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


Frank Hileman

unread,
Feb 20, 2006, 1:49:49 PM2/20/06
to
The Buffer class may be useful.

Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio graphics editor

"amaca" <pub...@ajam.net> wrote in message
news:e%23fw9XiN...@TK2MSFTNGP09.phx.gbl...

amaca

unread,
Feb 21, 2006, 3:46:47 AM2/21/06
to
It might indeed be, thank you.

Andrew


0 new messages