Extracting bytes from a 32-bit value
-
What would be a good C# programming manner to extract from a 32-bit value the different bytes (MSB to LSB) in big or little endian format?
Do an && to strip the bits you don't want, and shift them down with >>
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog
-
What would be a good C# programming manner to extract from a 32-bit value the different bytes (MSB to LSB) in big or little endian format?
There is an alternative, that may be interesting when many variables need to available in both packed and unpacked form. Using structs you can obtain a "union" effect in C# in the following way:
using System.Runtime.InteropServices; // StructLayout
[StructLayout(LayoutKind.Explicit)]
public struct Overlay {
[FieldOffset(0)]public uint u32;
[FieldOffset(0)]public byte u8_0;
[FieldOffset(1)]public byte u8_1;
[FieldOffset(2)]public byte u8_2;
[FieldOffset(3)]public byte u8_3;
}
public override void Run() {
Overlay overlay=new Overlay();
overlay.u32=0x12345678;
log("lo to hi: "+overlay.u8_0.ToString("X2")+" "+overlay.u8_1.ToString("X2")+
" "+overlay.u8_2.ToString("X2")+" "+overlay.u8_3.ToString("X2"));
}On a little-endian machine (such as Intel x86) the Run method will log "lo to hi: 78 56 34 12" Be careful though, you are responsible for the offset values ! :) -- modified at 11:54 Sunday 4th February, 2007
Luc Pattyn