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

6
  • 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. Commented Nov 28, 2022 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) Commented Nov 28, 2022 at 20:22
  • because I am storing pixels in this array (each pixel can have red,green,blue color (0xFFFFFF = white) Commented Nov 28, 2022 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?) Commented Nov 28, 2022 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. Commented Nov 28, 2022 at 20:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.