本文介绍了将字节数组转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#进行一些转换,但我不确定如何执行此操作:

I am trying to do some conversion in C#, and I am not sure how to do this:

private int byteArray2Int(byte[] bytes)
{
    // bytes = new byte[] {0x01, 0x03, 0x04};

    // how to convert this byte array to an int?

    return BitConverter.ToInt32(bytes, 0); // is this correct?
    // because if I have a bytes = new byte [] {0x32} => I got an exception
}

private string byteArray2String(byte[] bytes)
{
   return System.Text.ASCIIEncoding.ASCII.GetString(bytes);

   // but then I got a problem that if a byte is 0x00, it show 0x20
}

有人可以给我一些想法吗?

Could anyone give me some ideas?

推荐答案

BitConverter 是正确的方法.

您的问题是,当您答应32位时,您仅提供了8位.请改用数组中的有效32位数字,例如 new byte [] {0x32,0,0,0} .

Your problem is because you only provided 8 bits when you promised 32. Try instead a valid 32-bit number in the array, such as new byte[] { 0x32, 0, 0, 0 }.

如果要转换任意长度的数组,则可以自己实现:

If you want an arbitrary length array converted, you can implement this yourself:

ulong ConvertLittleEndian(byte[] array)
{
    int pos = 0;
    ulong result = 0;
    foreach (byte by in array) {
        result |= ((ulong)by) << pos;
        pos += 8;
    }
    return result;
}


目前尚不清楚问题的第二部分(涉及字符串)应该产生什么,但是我想您想使用十六进制数字吗? BitConverter 也可以提供帮助,如更早的问题中所述.

这篇关于将字节数组转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 17:57