Value Type Conversion to Array

  • Thread starter Thread starter David Kyle
  • Start date Start date
D

David Kyle

Just wondering if there's a quick way to convert types. I quite often have
things like an int that i want to convert the type to a byte array of length
4.

I guess the only way to do it is using unsafe code but even when doing that
I still have to copy the information to the array.

//this is what I would like to make work
int myInt = 244;
byte[] intAsBytes;

unsafe {
intAsBytes = &myInt;
}

//this is what I have to do
int myInt = 1;
byte[] intAsBytes = new byte[4];

unsafe {
byte* pointer = (byte*)&myInt;
for (int i = 0; i < 4; i++)
intAsBytes = *pointer++;
}
 
Yes, David. Use:

byte[] bytes = BitConverter.GetBytes(myInt);

HTH,
 
Awesome! Works like a charm! Thanks!

Cheers!

David Kyle
www.chloemag.com

Scott Allen said:
Yes, David. Use:

byte[] bytes = BitConverter.GetBytes(myInt);

HTH,

--
Scott
http://www.OdeToCode.com/blogs/scott/

Just wondering if there's a quick way to convert types. I quite often
have
things like an int that i want to convert the type to a byte array of
length
4.

I guess the only way to do it is using unsafe code but even when doing
that
I still have to copy the information to the array.

//this is what I would like to make work
int myInt = 244;
byte[] intAsBytes;

unsafe {
intAsBytes = &myInt;
}

//this is what I have to do
int myInt = 1;
byte[] intAsBytes = new byte[4];

unsafe {
byte* pointer = (byte*)&myInt;
for (int i = 0; i < 4; i++)
intAsBytes = *pointer++;
}

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top