【问题标题】:How to convert int[] to short[]?如何将 int[] 转换为 short[]?
【发布时间】:2017-06-01 09:06:19
【问题描述】:
int[] iBuf = new int[2];
iBuf[0] = 1;
iBuf[1] = 2;

short[] sBuf = new short[2];
Buffer.BlockCopy(iBuf, 0, sBuf, 0, 2);

result  
iBuf[0] = 1  
sBuf[0] = 1  
iBuf[1] = 2  
sBuf[1] = 0  

My desired result  
iBuf[0] = 1  
sBuf[0] = 1  
iBuf[1] = 2  
sBuf[1] = 2  

结果与我想要的不同。
有没有办法不使用循环进行转换?

【问题讨论】:

  • 简单的答案是否定的——int 使用 4 个字节,shorts 使用 2 个字节——所以本质上你需要复制交替的字节对。下面给出的答案将起作用 - 但在他们将使用循环的方法的覆盖下。根据数组的大小,可以使用您自己的方法编写更快的解决方案。

标签: c# arrays type-conversion


【解决方案1】:

您可以使用 Array.ConvertAll 方法。

例子:

int[]   iBuf = new int[2];
  ...
short[] sBuf = Array.ConvertAll(iBuf, input => (short) input);

此方法接受一个输入数组和一个转换器,结果将是您想要的数组。

编辑: 更短的版本是使用现有的 Convert.ToInt16 方法。在 ConvertAll 内:

int[] iBuf = new int[5];
short[] sBuf = Array.ConvertAll(iBuf, Convert.ToInt16);

那么,ConvertAll 是如何工作的?让我们看一下实现:

public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
{
    if (array == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
    }

    if (converter == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
    }

    Contract.Ensures(Contract.Result<TOutput[]>() != null);
    Contract.Ensures(Contract.Result<TOutput[]>().Length == array.Length);
    Contract.EndContractBlock();


    TOutput[] newArray = new TOutput[array.Length];

    for (int i = 0; i < array.Length; i++)
    {
        newArray[i] = converter(array[i]);
    }
    return newArray;
}

要回答实际问题...不,在某些时候将涉及一个循环来转换所有值。您可以自己编程,也可以使用已构建的方法。

【讨论】:

    【解决方案2】:

    int 是 32 位长,short 是 16 位长,所以这种复制数据的方式是行不通的。

    通用方法是创建一个将整数转换为短裤的方法:

    public IEnumerable<short> IntToShort(IEnumerable<int> iBuf)
    {
        foreach (var i in iBuf)
        {
            yield return (short)i;
        }
    }
    

    然后使用它:

    int[] iBuf = new int[2];
    iBuf[0] = 1;
    iBuf[1] = 2;
    
    short[] sBuf = IntToShort(iBuf).ToArray();
    

    【讨论】:

    • 当我可以用一行完成时,为什么创建其他方法是最简单的方法?
    • 当 .NET 已经提供此功能时,OP 是否有任何理由编写方法 - 请参阅 Milster 的回答。
    • 是的,但是如果他使用的是 .NET 2.0 或更早版本,那么他可以使用 LINQ 方法吗?
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多