none
Hex change Low to High order and then covert it into decimal RRS feed

  • Question

  • I have Hex string like 1480D604. Which I need to change order from Low to High 0x04D68014 and then I need to cast it into decimal value. One approach that I can think is first change their order first like.

    Step 1 : 14-80-D6-04 --> 04-D6-80-14

    How can I change this order from Low to High order in hex value.

    Step 2

    Cast output from first step into decimal value like this

    int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

    0x04D68014=81166356

    Is there any simple way to achieve this in single step.

    Tuesday, June 2, 2015 7:21 AM

Answers

  • Try this too:

    string hex = "1480D604";
    int value = IPAddress.NetworkToHostOrder( int.Parse( hex, NumberStyles.HexNumber ) );
    

    Tuesday, June 2, 2015 6:01 PM
  • Here is a function that takes a hex string, reverses it and then converts it to a signed integer. You didn't say what should happen if the original string in not 8 characters. In this function, if the original string is less than 8 characters, it is padded on the left with zeros, and if it is longer than 8 characters, only the left-most 8 are processed.

    public int RevHex(string hex) {
    	hex = hex.PadLeft(8, '0');
    	string rev = "";
    	for (int i = 6; i >= 0; i -= 2) {
    		rev += hex.Substring(i, 2);
    	}
    	return int.Parse(rev, System.Globalization.NumberStyles.HexNumber);
    }

    Tuesday, June 2, 2015 2:55 PM

All replies

  • Here is a function that takes a hex string, reverses it and then converts it to a signed integer. You didn't say what should happen if the original string in not 8 characters. In this function, if the original string is less than 8 characters, it is padded on the left with zeros, and if it is longer than 8 characters, only the left-most 8 are processed.

    public int RevHex(string hex) {
    	hex = hex.PadLeft(8, '0');
    	string rev = "";
    	for (int i = 6; i >= 0; i -= 2) {
    		rev += hex.Substring(i, 2);
    	}
    	return int.Parse(rev, System.Globalization.NumberStyles.HexNumber);
    }

    Tuesday, June 2, 2015 2:55 PM
  • Try this too:

    string hex = "1480D604";
    int value = IPAddress.NetworkToHostOrder( int.Parse( hex, NumberStyles.HexNumber ) );
    

    Tuesday, June 2, 2015 6:01 PM