How to Convert a byte array into an int array? I have a byte array holding 144 items and the ways I have tried are quite inefficient due to my inexperience. I am sorry if this has been answered before, but I couldn't find a good answer anywhere.
Simple:
//Where yourBytes is an initialized byte array.
int[] bytesAsInts = yourBytes.Select(x => (int)x).ToArray();
Make sure you include System.Linq with a using declaration:
using System.Linq;
And if LINQ isn't your thing, you can use this instead:
int[] bytesAsInts = Array.ConvertAll(yourBytes, c => (int)c);
I known this is an old post, but if you were looking in the first place to get an array of integers packed in a byte array (and it could be considering your array byte of 144 elements), this is a way to do it:
var size = bytes.Count() / sizeof (int);
var ints = new int[size];
for (var index = 0; index < size; index++)
{
ints[index] = BitConverter.ToInt32(bytes, index * sizeof (int));
}
Note: take care of the endianness if needed. (And in most case it will)
Use Buffer.BlockCopy instead of Array.ConvertAll.
ref Converting an int[] to byte[] in C#
byte[] bytes = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 };
int[] ints= Array.ConvertAll(bytes, Convert.ToInt32);
will return ints[]={0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8},
not return ints[]={0x04030201,0x08070605}
should use
Buffer.BlockCopy(bytes, 0, ints, 0, bytes.Length);
Now It's Simple like follows,
int[] result = Array.ConvertAll(bytesArray, Convert.ToInt32);
Related
This might be a simple one, but I can't seem to find an easy way to do it. I need to save an array of 84 uint's into an SQL database's BINARY field. So I'm using the following lines in my C# ASP.NET project:
//This is what I have
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = ???
cmd.Parameters.Add("#myBindaryData", SqlDbType.Binary).Value = byteArray;
So how do you convert from uint[] to byte[]?
How about:
byte[] byteArray = uintArray.SelectMany(BitConverter.GetBytes).ToArray();
This'll do what you want, in little-endian format...
You can use System.Buffer.BlockCopy to do this:
byte[] byteArray = new byte[uintArray.Length * 4];
Buffer.BlockCopy(uintArray, 0, byteArray, 0, uintArray.Length * 4];
http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx
This will be much more efficient than using a for loop or some similar construct. It directly copies the bytes from the first array to the second.
To convert back just do the same thing in reverse.
There is no built-in conversion function to do this. Because of the way arrays work, a whole new array will need to be allocated and its values filled-in. You will probably just have to write that yourself. You can use the System.BitConverter.GetBytes(uint) function to do some of the work, and then copy the resulting values into the final byte[].
Here's a function that will do the conversion in little-endian format:
private static byte[] ConvertUInt32ArrayToByteArray(uint[] value)
{
const int bytesPerUInt32 = 4;
byte[] result = new byte[value.Length * bytesPerUInt32];
for (int index = 0; index < value.Length; index++)
{
byte[] partialResult = System.BitConverter.GetBytes(value[index]);
for (int indexTwo = 0; indexTwo < partialResult.Length; indexTwo++)
result[index * bytesPerUInt32 + indexTwo] = partialResult[indexTwo];
}
return result;
}
byte[] byteArray = Array.ConvertAll<uint, byte>(
uintArray,
new Converter<uint, byte>(
delegate(uint u) { return (byte)u; }
));
Heed advice from #liho1eye, make sure your uints really fit into bytes, otherwise you're losing data.
If you need all the bits from each uint, you're gonna to have to make an appropriately sized byte[] and copy each uint into the four bytes it represents.
Something like this ought to work:
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = new byte[uintArray.Length * sizeof(uint)];
for (int i = 0; i < uintArray.Length; i++)
{
byte[] barray = System.BitConverter.GetBytes(uintArray[i]);
for (int j = 0; j < barray.Length; j++)
{
byteArray[i * sizeof(uint) + j] = barray[j];
}
}
cmd.Parameters.Add("#myBindaryData", SqlDbType.Binary).Value = byteArray;
Say I have an array like this:
byte[] arr = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}
Can I somehow iterate through it with elements treated like Uint16? I want to make my application to treat it like {0x1122, 0x3344, 0x5566, 0x7788}.
Tried using as keyword but the compiler woudn't let me:
byte[] bytearray = new byte[10];
UInt16[] uint16array = bytearray as UInt16[];
Is there any way to do it? (without creating another array or casting two bytes into one uint16 every iteration)
this little helper method should help you
public static class helper
{
public static UInt16[] ToUnit16(this byte[] arr)
{
if (arr == null)
return null;
var len = arr.Length;
if ((len % 2) != 0)
throw new ArgumentException("Must divide by 2");
var count = len / 2;
var result = new UInt16[count];
do
{
result[--count] = (UInt16)((arr[--len]) | arr[--len] << 8);
} while (count > 0);
return result;
}
}
No, C# doesn't offer a way to safely reinterpret one object as if it were some different type of object (you can do it with unsafe code, but then the whole assembly winds up "unsafe").
You can use BitConverter.ToUInt16(), or even wrap the byte[] in a MemoryStream and use the BinaryReader.ReadUInt16() method to read from the byte[] object. But judging from the wording of the question, you don't want to use any method like that.
You can do it with unsafe code:
fixed(byte* p = bytearray)
{
ushort* ptr=(ushort*)p;
for(int i = 0; i < bytearray.Length/2; i++)
{
//...
}
}
You cannot cast the entire array like that, at least not in managed code. You can convert this using BitConverter.ToUInt16, like this:
UInt16[] uint16array = Enumerable
.Range(0, arr.Length/2)
.Select(i => BitConverter.ToUInt16(arr, 2*i))
.ToArray();
byte checksum;
byte[] toBuff = new byte[20];
toBuff = BitConverter.GetBytes(intNumBuffer);
Array.Reverse(mybyte);
checksum = ComputeChecksum(toBuff); //int to byte array
// At this point, the array is something like this
// toBuff[0] = 25
// toBuff[1] = 0
// toBuff[2] = 0
// toBuff[3] = 0
toBuff[4] = checksum; //HERE IS WHERE OUR OF BOUNDS OCCURS
I am new and would greatly appreciate any help.
Thanks
toBuff = BitConverter.GetBytes(intNumBuffer);
The call to BitConverter.GetBytes() returns a byte array of length 4, because intNumBuffer is an int, which has size 4.
So, that means that the valid indices of toBuff are 0, 1, 2 and 3. Hence the error when you use index 4.
Now, I suppose that you imagined that when you wrote:
byte[] toBuff = new byte[20];
that toBuff would have length 20. Well, it does at this point. But when you subsequently overwrite toBuff, then you have a new and different array.
Probably what you need to do is as follows:
byte[] toBuff = new byte[20];
Array.Copy(BitConverter.GetBytes(intNumBuffer), toBuff, sizeof(int));
Or perhaps:
byte[] toBuff = new byte[20];
byte[] intBytes = BitConverter.GetBytes(intNumBuffer);
Array.Copy(intBytes, toBuff, intBytes.Length);
Either of these will copy the bits returned by the call to GetBytes() into toBuff.
This is normal, because you only add an item in the range of 0 to 3.
You could check first if the toBuff[someIndex] actually has a value and thus is not null.
BitCOnverter.GetBytes return an array of 4 check :http://msdn.microsoft.com/en-us/library/de8fssa4(v=vs.110).aspx
toBuff = BitConverter.GetBytes(intNumBuffer);
Okay, I'm trying to convert a byte[] to a short[], or Int16[].
List<Int16[]> lol = new List<Int16[]>();
byte[] b = System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
lol.Add(Convert.ToInt16(b));
MessageBox.Show(Encoding.Default.GetString(Encoding.Default.GetBytes(lol[0])));
That is something that I tried, but obviously, it doesn't work. So how would I do this?
It looks to me like you want to convert an entire array in one line. It could be done like this:
List<Int16[]> lol = new List<Int16[]>();
byte[] b = System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
lol.Add(Array.ConvertAll(b, x => Convert.ToInt16(x)));
You have to go through the byte array, and convert each element.
List<Int16[]> lol=new List<Int16[]>();
byte [] b=System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
Int16 [] a=new Int16 [b.Length];
for (Int32 i=0;i<a.Length;++i) {
a[i]=Convert.ToInt16(b[i]);
}
lol.Add(a);
You probably want BitConverter.ToInt16(), which you'd need to call for each pair of bytes.
Or, use Buffer.BlockCopy to do it all at once (using the machine's native byte order).
byte[] by = new byte[5];
short[] sh = new short[5];
by[0] = 0x1;
by[1] = 0x2;
by[2] = 0x3;
by[3] = 0x4;
by[4] = 0x5;
for (int x = 0; x < sh.GetLength(0); x++)
{
sh[x] = by[x];
MessageBox.Show(by[x].ToString());
That worked for me. Not sure if I am misunderstanding or not.
I'm trying to convert an int value to a byte array, but I'm using the byte for MIDI information (meaning that the 0x00 byte which is returned when using GetBytes acts as a separator) which renders my MIDI information useless.
I would like to convert the int to an array which leaves out the 0x00 bytes and just contains the bytes which contain actual values. How can I do this?
You've completely misunderstood what you need, but luckily you mentioned MIDI. You need to use the multi-byte encoding that MIDI defines, which is somewhat similar to UTF-8 in that less than 8 bits of data are placed into each octet, with the remaining providing information about the number of bits used.
See the description on wikipedia. Pay close attention to the fact that protobuf uses this encoding, you can probably reuse some of Google's code.
Based on the info Ben added, this should do what you require:
static byte[] VlqEncode(int value)
{
uint uvalue = (uint)value;
if (uvalue < 128) return new byte[] { (byte)uvalue }; // simplest case
// calculate length of buffer required
int len = 0;
do {
len++;
uvalue >>= 7;
} while (uvalue != 0);
// encode (this is untested, following the VQL/Midi/protobuf confusion)
uvalue = (uint)value;
byte[] buffer = new byte[len];
for (int offset = len - 1; offset >= 0; offset--)
{
buffer[offset] = (byte)(128 | (uvalue & 127)); // only the last 7 bits
uvalue >>= 7;
}
buffer[len - 1] &= 127;
return buffer;
}