Convert int[] to byte[] type pointer in C#

你离开我真会死。 提交于 2019-12-24 02:39:11

问题


I require to convert int[] to byte[] pointer. The above is required in order to be able to populate the entries of a WriteableBitmap pixel by pixel as below:

//previewBuffer1 is of type byte[]
WriteableBitmap wb1 = new WriteableBitmap(nVidWidth, nVidHeight);
int k=0;
// wb1.Pixels is of type int[] by default
byte* data = (byte*) wb1.Pixels;  // ****THIS DOESN'T WORK. THROWS ERROR. HOW CAN I ACCOMPLISH THIS***
for (int i=0; i<nVidHeight; i++){
    for (int j=0; j<nVidWidth; j++){
        byte grayscaleval = previewBuffer1[k];
        data [4*k] = grayscaleval ;
        data [4*k + 1] = grayscaleval ;
        data [4*k + 2] = grayscaleval ;
        k++;
    }
}

How do I get a byte* pointer for wb1.Pixels which is of type int[]?


回答1:


Sounds like you want to treat each int in your array as sequence of bytes - how about BitConverter.GetBytes?

byte[] bytes = BitConverter.GetBytes(intValue);

If you want to avoid array copying etc, use unsafe which allows pointers (you'd need to tick the "Allow unsafe code" checkbox in project properties):

unsafe static void UnsafeConvert(int value)
{
    byte* bytes = (byte*)&value;
    byte first = bytes[0];
    ...
}



回答2:


I'm confused by your loop because I think it has a few problems...but it looks like you are trying to strip the alpha component of RGBA data. Why not do something like:

Assuming you have: 1. a byte [] you want to store RGB data without the Alpha component 2. an int [] source of RGBA data

int offset=0; // offset into the 'dest' array of bytes

for (...) // loop through your source array of ints 
{
    // get this current int value as rgba_val
    int rgba_val = (whatever your RGBA source is..is it wb1.Pixels?)

    dest[offset] = (rgba_val & 0xff) >> 24;
    dest[offset+1] = (rgba_val & 0x00ff) >> 16;
    dest[offset+2] = (rgba_val & 0x0000ff) >> 8;
}



回答3:


I guess the below will work out for me:

//previewBuffer1 is of type byte[]
WriteableBitmap wb1 = new WriteableBitmap(nVidWidth, nVidHeight);
int k=0;
// wb1.Pixels is of type int[] by default
//byte* data = (byte*) wb1.Pixels;  // ****NOT REQUIRED ANYMORE***
for (int i=0; i<nVidHeight; i++){
    for (int j=0; j<nVidWidth; j++){
        int grayscaleval = (int) previewBuffer1[k];
        wb1.Pixels[k] = ((grayscaleval) | (grayscaleval<<8) | (grayscaleval<<16) | (0xFF<<24)); // 0xFF is for alpha blending value

        k++;
    }
}

Atleast logically seems to be fine. Yet to try it out.




回答4:


Use this to convert your int array into bytes array

WriteableBitmap wb1 = new WriteableBitmap(100, 100);
int[] pixels = wb1.Pixels;
byte[] data = new byte[pixels.Length];
for (int i= 0; i < pixels.Length;i ++)
{
    data[i] = (byte)pixels[i];
}


来源:https://stackoverflow.com/questions/17714662/convert-int-to-byte-type-pointer-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!