Sunday, May 1, 2011

C#: Convert a UInt16 in string format into an integer(decimal)

Here's the problem.

I ,for example,have a string "2500".Its converted from byte array into string.I have to convert it to decimal(int).

This is what I should get:

string : "2500"
byte[] : {0x25, 0x00}
UInt16 : 0x0025 //note its reversed
int    : 43     //decimal of 0x0025

How do I do that?

From stackoverflow
  • Converting from hex string to UInt16 is UInt16.Parse(s, NumberStyles.AllowHexSpecifier).

    You'll need to write some code to do the "reversal in two-digit blocks" though. If you have control over the code that generates the string from the byte array, a convenient way to do this would be to build the string in reverse, e.g. by traversing the array from length - 1 down to 0 instead of in the normal upward direction. Alternatively, assuming that you know it's exactly a 4 character string, s = s.Substring(2, 2) + s.Substring(0, 2) would do the trick.

  • It might be better to explicitly specify what base you want with Convert.ToUInt16.

    Then, you can flip it around with IPAddress.HostToNetworkOrder (though you'll have to cast it to an int16, then cast the result back to a uint16.

  • there is a special class for conversion : Convert to convert from string to uint16 use the following method: Convert.ToUInt16

    for difference on int.parse and Convert.ToInt32 is explained in this page

    and the msdn site for Convert.ToUInt16 here

  • Assuming your string is always 4 digits long. You can get away with one string variable but I'm using multiple ones for readability.

    string originalValue = "2500";
    string reverseValue = originalValue.Substring(2, 2) + originalValue.Substring(0, 2);
    string hexValue = Convert.ToUInt16(reverseValue, 16).ToString();
    int result = Convert.ToInt32(hexValue, 10);
    

0 comments:

Post a Comment