/// <summary> /// Convert an object into string representation. /// Dictionary, Enumerable, DictionaryEntry and Class are /// simply converted to string...(not supported essentially) /// DateTime is always returned as ddMMyyyy HHmmss /// Semi-Colon (;) in data are converted to ~ and comma(,) in data are converted to ` /// </summary> /// <param name="obj">Object instance to convert to JSON</param> /// <returns>string</returns> protected static string AsString(Object obj) { if (obj == null) { return(""); } Type type = obj.GetType(); string objAsStr = obj.ToString(); objAsStr = AbstractStringUtils.Replace(objAsStr, ';', '~'); objAsStr = AbstractStringUtils.Replace(objAsStr, ',', '`'); switch (type.Name) { case "Boolean": return(((bool)obj) ? "true" : "false"); case "String": case "Char": case "Guid": return("\"" + objAsStr + "\""); case "Single": case "Double": case "Decimal": case "Float": case "Byte": case "SByte": case "Int16": case "UInt16": case "Int32": case "UInt32": case "Int64": case "UInt64": return(objAsStr); case "DateTime": DateTime dt = (DateTime)obj; return("\"" + AbstractStringUtils.PadLeft(dt.Day.ToString(), '0', 2) + AbstractStringUtils.PadLeft(dt.Month.ToString(), '0', 2) + AbstractStringUtils.PadLeft(dt.Year.ToString(), '0', 4) + " " + AbstractStringUtils.PadLeft(dt.Hour.ToString(), '0', 2) + AbstractStringUtils.PadLeft(dt.Minute.ToString(), '0', 2) + AbstractStringUtils.PadLeft(dt.Second.ToString(), '0', 2) + "\""); default: return("\"" + objAsStr + "\""); } }
/// <summary> /// Convert a string representing a hexadecimal number to UInt32 /// </summary> /// <param name="hexStr">The hex string</param> /// <returns>The unsigned integer representation of the hex string</returns> public static UInt32 Hex2UInt32(string hexStr) { if (hexStr == null) { throw new ArgumentNullException("Hex string is null"); } if (hexStr.Trim().Length == 0) { throw new ArgumentException("Hex string is empty"); } hexStr = (hexStr.Trim().IndexOf("0x") == 0) ? hexStr.Trim().Substring(2).ToUpper() : hexStr.Trim().ToUpper(); if (hexStr.Length > 8) //more than 4 bytes or 8-nibbles { throw new ArgumentException("Hex string too large for conversion"); } ArrayList allowedHexChars = new ArrayList(); char[] hexCharArr = "0123456789ABCDEF".ToCharArray(); foreach (char hexChar in hexCharArr) { allowedHexChars.Add(hexChar); } //check if the hex string contains dis-allowed characters char[] hexChars = AbstractStringUtils.PadLeft(hexStr, '0', 8).ToCharArray(); foreach (char hex in hexChars) { if (!allowedHexChars.Contains(hex)) { throw new ArgumentException("Input string does not represent hexadecimal characters"); } } UInt32 mul = 1; UInt32 result = 0; for (int count = hexChars.Length - 1; count >= 0; --count) { result += (UInt32)(mul * (allowedHexChars.IndexOf(hexChars[count]))); mul = (uint)(mul * allowedHexChars.Count); } return(result); }