0

I have an UINT32 array filled with bytes, because my value is too long it has to be in uint32 because byte array is just to short for it

UInt32[] somebytes = new UInt32[] { 0xAABBCC, 0xAABBCC };

but whats inside is 0x00AABBCC, 0x00AABBCC

and because of that my function that should return first 2 bytes in every row

[0] = 0xAA
[1] = 0xAA

returns

[0] = 0x00
[1] = 0x00

here is my function, that should return first 2 bytes (my brain tells me that first 2 bytes are 0xAA)

public byte[] GetRed(UInt32[] buffer)
{
    byte[] output = new byte[buffer.Length];
    for (int i = 0; i < output.Length; i++)
    {
        byte b = (byte)buffer[i];
        output[i] = (byte)(b & 0xFFFF);   //fist 2 bytes
    }
    return output;
}

I hope someone has an idea, on whats going on and how to fix all this Thsnk

LimetaPeta
  • 67
  • 5
  • 3
    The first byte of `0x00AABBCC` is `0x00`, not `0xAA`. Why not store your values in a `byte[]` and not worry about endian-ness and everything else that you get with multi-byte integral types. Otherwise, learn how to do bit sizzling with shifts and masks. – Flydog57 Nov 28 '22 at 20:17
  • 3
    you have a few problems here. First, as Flydog pointed out, the first byte of `0xAABBCC` is `0x00` when it is stored in a `UInt32` variable. But also, your bitmask is wrong and your cast to `byte` is cutting off the data you want. the bitmask `0xFFFF` will select the opposite of what you want (`0xBBCC`) so you need to do `b & 0xFF0000` and then you need to right shift it 16 bits so that the data is in the LSBs when you cast to `byte` So your whole operation would be `(byte)((b & 0xFF0000) >> 16)` – frankM_DN Nov 28 '22 at 20:22
  • because I am storing pixels in this array (each pixel can have red,green,blue color (0xFFFFFF = white) – LimetaPeta Nov 28 '22 at 20:46
  • @frankM_DN thanks, that did the trick, (I guess I should practise bit manipulations a bit, its always so confusing, you write your bitmask on paper (you turn on all the bits you want to omit, but for some reason its still wrong :) ) BTW: why did you shift by 16 instead of 32? (isnt uint32 32bits, so if you want to move your desired bits to the most right (LSB, you shift by 32?) – LimetaPeta Nov 28 '22 at 20:55
  • 3
    @LimetaPeta, shifting right by 32 bits would shift all of the bits in a `UInt32` out and you would just be left with `0`! If we look at `0x00AABBCC`, `AA` is in bits 16 - 23 and you need them in bits 0 - 7 (so that they can be put into a `byte` variable. So that means we need to shift right 16 bits. – frankM_DN Nov 28 '22 at 20:59
  • Here's the most complex example of bit swizzling I can think of. It might give you some ideas (my answer) https://stackoverflow.com/questions/55499116/c-sharp-extract-bit-ranges-from-byte-array/55505757#55505757 – Flydog57 Nov 28 '22 at 21:16

0 Answers0