Convert byte array to int

前端 未结 4 1123
既然无缘
既然无缘 2021-01-04 18:03

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, 0         


        
4条回答
  •  梦毁少年i
    2021-01-04 18:50

    BitConverter is the correct approach.

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

    It's not clear what the second part of your question (involving strings) is supposed to produce, but I guess you want hex digits? BitConverter can help with that too, as described in an earlier question.

提交回复
热议问题