Conversion of byte array containing hex values to decimal values

前端 未结 5 1988
一生所求
一生所求 2021-01-01 04:17

I am making application in c#.Here i want to convert a byte array containing hex values to decimal values.Suppose i have one byte array as

array[0]=0X4E;
ar         


        
相关标签:
5条回答
  • 2021-01-01 04:52

    The BitConverter.ToInt32 method is a good way to do this

    if (BitConverter.IsLittleEndian)
        Array.Reverse(array); //need the bytes in the reverse order
    int value = BitConverter.ToInt32(array, 0);
    
    0 讨论(0)
  • 2021-01-01 04:57

    Instead of checking IsLittleEndian by yourself, you can use IPAddress.NetworkToHostOrder(value).

    int value = BitConverter.ToInt32(array, 0);
    
    value = IPAddress.NetworkToHostOrder(value);
    

    See more:

    https://docs.microsoft.com/de-de/dotnet/api/system.net.ipaddress.networktohostorder?redirectedfrom=MSDN&view=netframework-4.7.2#System_Net_IPAddress_NetworkToHostOrder_System_Int32_

    0 讨论(0)
  • 2021-01-01 05:11

    Mind the byte order.

    int num = 
        array[0] << 8 * 3 | 
        array[1] << 8 * 2 | 
        array[2] << 8 * 1 | 
        array[3] << 8 * 0;
    
    0 讨论(0)
  • 2021-01-01 05:15

    hex and decimal are just different ways to represent the same data you want something like

    int myInt = array[0] | (array[1] << 8) | (array[2] << 16) | (array[3] <<24)
    
    0 讨论(0)
  • 2021-01-01 05:16

    Here's a method to convert a string containing a hexadecimal number to a decimal integer:

    private int HexToDec(string hexValue)
    {
        char[] values = hexValue.ToUpperInvariant().ToCharArray();
        Array.Reverse(values);
        int result = 0;
        string reference = "0123456789ABCDEF";
    
        for (int i = 0; i < values.Length; i++)
            result += (int)(reference.IndexOf(values[i]) * Math.Pow(16d, (double)i));
    
        return result;
    }
    

    You can then string the pieces together and pass them to this function to get the decimal values. If you're using very large values, you may want to change from int to ulong.

    0 讨论(0)
提交回复
热议问题