相关疑难解决方法(0)

C#不安全值类型数组到字节数组转换

我使用扩展方法将float数组转换为字节数组:

public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
{
    int arrayLength = floatArray.Length > count ? count : floatArray.Length;
    byte[] byteArray = new byte[4 * arrayLength];
    fixed (float* floatPointer = floatArray)
    {
        fixed (byte* bytePointer = byteArray)
        {
            float* read = floatPointer;
            float* write = (float*)bytePointer;
            for (int i = 0; i < arrayLength; i++)
            {
                *write++ = *read++;
            }
        }
    }
    return byteArray;
}
Run Code Online (Sandbox Code Playgroud)

我知道数组是指向与元素类型和数量信息相关的内存的指针.此外,在我看来,如果没有像上面那样复制数据,就没有办法从字节数组转换到字节数组.

我明白了吗?甚至不可能编写IL来从指针,类型和长度创建数组而不复制数据?

编辑:谢谢你的答案,我学到了一些基础知识,并尝试了新的技巧!

在最初接受Davy Landman的回答之后,我发现虽然他出色的StructLayout hack确实将字节数组转换为浮点数组,但它却无法正常工作.展示:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public …
Run Code Online (Sandbox Code Playgroud)

c# arrays pointers unsafe type-conversion

10
推荐指数
2
解决办法
2万
查看次数

将字节数组转换为double的问题

我有一个问题,使用转换字节数组到双数组BitConverter.ToDouble().

只需我的程序将选择一个图像,然后将图像转换为字节数组.然后它将字节数组转换为双数组.

当我将字节数组转换为double时,我将在循环结束前得到此错误的问题.

(目标数组不够长,无法复制集合中的所有项目.检查数组索引和长度.)

该错误恰好发生在array.Length-7位置,该位置是阵列上最后一个位置之前的第七个位置.

我需要帮助来解决这个问题,这是我的代码:

private Bitmap loadPic;
byte[] imageArray;
double[] dImageArray;

private void btnLoad_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog open = new OpenFileDialog();
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

        if (open.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Image = new Bitmap(open.FileName);
            loadPic = new Bitmap(pictureBox1.Image);
        }
    }
    catch
    {
        throw new ApplicationException("Failed loading image");
    }

    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}

private void btnConvert_Click(object sender, EventArgs e)
{
    imageArray =  imageToByteArray(loadPic);
    int index = imageArray.Length; …
Run Code Online (Sandbox Code Playgroud)

c# winforms

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

arrays ×1

pointers ×1

type-conversion ×1

unsafe ×1

winforms ×1