在C#中将int[]转换为byte[]类型的指针

本文关键字:byte 类型 指针 转换 int 中将 | 更新日期: 2023-09-27 18:23:36

我需要将int[]转换为byte[]指针。为了能够逐个像素填充可写位图的条目,需要上述内容,如下所示:

//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++;
    }
}

如何为类型为int[]的wb1.Pixels获取字节*指针?

在C#中将int[]转换为byte[]类型的指针

听起来您想将数组中的每个int都视为字节序列,那么BitConverter.GetBytes呢?

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

如果你想避免数组复制等,请使用允许指针的unsafe(你需要在项目属性中勾选"允许不安全代码"复选框):

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

我对你的循环感到困惑,因为我认为它有一些问题。。。但看起来你正试图剥离RGBA数据中的阿尔法成分。为什么不做一些类似的事情:

假设您已经:1.要存储不带Alpha组件的RGB数据的字节[]2.RGBA数据的int[]源

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;
}

我想下面的内容会对我有用:

//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++;
    }
}

至少从逻辑上来说似乎是好的。但要尝试一下。

使用它将int数组转换为字节数组

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];
}