Convert integer to hexadecimal and back again

前端 未结 10 2304
轮回少年
轮回少年 2020-11-22 02:33

How can I convert the following?

2934 (integer) to B76 (hex)

Let me explain what I am trying to do. I have User IDs in my database that are stored as inte

10条回答
  •  轮回少年
    2020-11-22 02:58

    Try the following to convert it to hex

    public static string ToHex(this int value) {
      return String.Format("0x{0:X}", value);
    }
    

    And back again

    public static int FromHex(string value) {
      // strip the leading 0x
      if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
        value = value.Substring(2);
      }
      return Int32.Parse(value, NumberStyles.HexNumber);
    }
    

提交回复
热议问题