471,627 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,627 software developers and data experts.

Integers to Bit Array


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
Feb 20 '06 #1
4 2680
amaca wrote:
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

Feb 20 '06 #2
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
Feb 20 '06 #3
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" <pu****@ajam.net> wrote in message
news:e%****************@TK2MSFTNGP09.phx.gbl...

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

Feb 20 '06 #4
It might indeed be, thank you.

Andrew
Feb 21 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.