0

I have an Int32 that is broken in to different sections, each with its own value.

Lets say I have:

byte version = 0x02
uInt32 packedValues = 0; 

How can I put the 0x02 in packedValues, starting at index 20, or any index.

Thanks!

Azriel H
  • 45
  • 4
  • What is the layout of this int32? Is it a bunch of bit flags or do you intend to have multibit fields? – jwdonahue May 04 '23 at 22:20
  • Multibig fields I guess? Like on the decoder side, for example bits 11-13 is a sequence number. So to decode it, the other end would just look at those bits bits, then cast it to a number. So if the sequence is bit11-13 is "0x111", the number casted should be decimal 7. – Azriel H May 04 '23 at 22:24
  • Why not use a struct? – jwdonahue May 04 '23 at 22:29
  • Does this answer your question? [Bit fields in C#](https://stackoverflow.com/questions/14464/bit-fields-in-c-sharp) – jwdonahue May 04 '23 at 22:35
  • My personal inclination would be to define field masks and apply those to the unit32: `unit32 fieldA = 0x3; // Lowest 2 bits, etc.` – jwdonahue May 04 '23 at 22:40
  • Right, I was going that route. So to set fieldA i would just OR then together no? packedValues = packedValues | fieldA ? No bitshifting is required, i think – Azriel H May 04 '23 at 23:06

2 Answers2

3

Not sure what do you mean by index but it seems that you need to do some bit twiddling. Something along these lines:

byte version = 0x02;
var index = 20;
uint packedValues = 0;

var b1 = version << index;
packedValues = (uint)((packedValues & ~(0xFF << index)) | (uint)(version << index));

(packedValues & ~(0xFF << index)) - zeroes needed bits and the rest sets the bits from the source.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Bit twiddling rather than bit arithmetic. There isn't much arithmetic in `&` `|` `~` and `<<`. Good answer anyway. – Charlieface May 04 '23 at 23:38
0

You can us a span<byte> to convert your int to a collection of bytes. Can't test right now but something like

Span<byte> bytes = BitConverter.GetBytes(packedValues);

bytes[20] = 0x02;

uint32 packedValues = BitConverter.ToInt32(ItemLengthBytes);
Jay
  • 2,553
  • 3
  • 17
  • 37