Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlockCopy alternative that allows me to choose endianness

Tags:

c#

endianness

Say I have an array of bytes:

byte[] input = { 0xFF, 0xFc, 0x00, 0x00 }

You can use Buffer.BlockCopy to copy bytes from one array to another, regardless of type. So, I can do this:

uint[] output = new uint[1];
Buffer.BlockCopy(input , 0, output, 0, input.Length);

This will copy the bytes from input to output, converting them from an array of bytes to an array of uints along the way.

The problem is that BlockCopy interprets the bytes with little endianness. I need a copy that uses big endianness. So rather than getting a uint value of 4294705152 (0xFFFC0000), like I need, I get the value 64767 (0x0000FCFF). Note that this is a bare-bones example, I cannot easily reverse the order of the bytes in my actual application.

Is there anything with the convenience and speed of BlockCopy that includes the ability to set the endianness I need?

like image 272
jpreed00 Avatar asked Oct 20 '22 12:10

jpreed00


1 Answers

The topic seems to be covered here:

How to get little endian data from big endian in c# using bitConverter.ToInt32 method?

However the conversion has to be iterated on the entire input array.

like image 162
Codor Avatar answered Oct 23 '22 01:10

Codor