I am trying to convert datetime to hex and send it to another page in query string and I am trying to convert the Hex to date time again. I have converting datetime to HEX like this
private string DateToHex(DateTime theDate)
{
string isoDate = theDate.ToString("yyyyMMddHHmmss");
string xDate = (long.Parse(isoDate)).ToString("x");
string resultString = string.Empty;
for (int i = 0; i < isoDate.Length - 1; i++)
{
int n = char.ConvertToUtf32(isoDate, i);
string hs = n.ToString("x");
resultString += hs;
}
return resultString;
}
By converting Datetime to HEx I got like this 32303134303631313136353034 and in another page I am trying to convert the hex to Date time like this
private DateTime HexToDateTime(string hexDate)
{
int secondsAfterEpoch = Int32.Parse(hexDate, System.Globalization.NumberStyles.HexNumber);
DateTime epoch = new DateTime(1970, 1, 1);
DateTime myDateTime = epoch.AddSeconds(secondsAfterEpoch);
return myDateTime;
}
I have tried this to Convert HEX to DateTime
string sDate = string.Empty;
for (int i = 0; i < hexDate.Length - 1; i++)
{
string ss = hexDate.Substring(i, 2);
int nn = int.Parse(ss, NumberStyles.AllowHexSpecifier);
string c = Char.ConvertFromUtf32(nn);
sDate += c;
}
CultureInfo provider = CultureInfo.InvariantCulture;
CultureInfo[] cultures = { new CultureInfo("fr-FR") };
return DateTime.ParseExact(sDate, "yyyyMMddHHmmss", provider);
It shows the eoor like this Value was either too large or too small for an Int32.. Any solution are surely appretiated.
any solution are sure appratiated
The DateTime value is already stored internally as a long, so you don't have to make a detour to create a long value. You can just get the internal value and format it as a hex string:
private string DateToHex(DateTime theDate) {
return theDate.ToBinary().ToString("x");
}
Converting it back is as easy:
private DateTime HexToDateTime(string hexDate) {
return DateTime.FromBinary(Convert.ToInt64(hexDate, 16));
}
Note: This also retains the timezone settings that the DateTime value contains, as well as the full precision down to 1/10000 second.
I can spot two logic errors.
Your DateToHex routine is ignoring the last character. It should be
private string DateToHex(DateTime theDate)
{
string isoDate = theDate.ToString("yyyyMMddHHmmss");
string resultString = string.Empty;
for (int i = 0; i < isoDate.Length ; i++) // Amended
{
int n = char.ConvertToUtf32(isoDate, i);
string hs = n.ToString("x");
resultString += hs;
}
return resultString;
}
Your routine to convert from hex to string should be advancing two characters at a time , ie
string hexDate = DateToHex(DateTime.Now);
string sDate = string.Empty;
for (int i = 0; i < hexDate.Length - 1; i += 2) // Amended
{
string ss = hexDate.Substring(i, 2);
int nn = int.Parse(ss, NumberStyles.AllowHexSpecifier);
string c = Char.ConvertFromUtf32(nn);
sDate += c;
}
CultureInfo provider = CultureInfo.InvariantCulture;
CultureInfo[] cultures = { new CultureInfo("fr-FR") };
return DateTime.ParseExact(sDate, "yyyyMMddHHmmss", provider);
Try this. I hope this will solve your purpose. I have tested it and it seems to be working fine.
Convert it to DateTime-> string-> Hex
string input = DateTime.Now.ToString("yyyyMMddHHmmss");
string hexValues = "";
int value = 0;
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
hexValues += String.Format("{0:X}", value);
hexValues += " ";
}
Now convert it again to HEX-> string-> DateTime
string stringValue = "";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
if (hex != "")
{
value = Convert.ToInt32(hex, 16);
// Get the character corresponding to the integral value.
stringValue += Char.ConvertFromUtf32(value);
}
}
DateTime dt = DateTime.ParseExact(stringValue, "yyyyMMddHHmmss", null);
To convert from hex to time.
Input : 0060CE5601D6CE01
Output : 31-10-2013 06:20:48
string hex1;
string[] hex = new string[16];
hex[0] = hex1.Substring(0, 2);
hex[1] = hex1.Substring(2, 2);
hex[2] = hex1.Substring(4, 2);
hex[3] = hex1.Substring(6, 2);
hex[4] = hex1.Substring(8, 2);
hex[5] = hex1.Substring(10, 2);
hex[6] = hex1.Substring(12, 2);
hex[7] = hex1.Substring(14, 2);
//WE DONOT NEED TO REVERSE THE STRING
//CONVERTING TO INT SO WE CAN ADD TO THE BYTE[]
int[] decValue = new int[8];
for (int i = 0; i < 8; i++)
{
decValue[i] = Convert.ToInt32(hex[i], 16);
}
//CONVERTING TO BYTE BEFORE WE CAN CONVERT TO UTC
byte[] timeByte = new byte[8];
for (int i = 0; i < 8; i++)
timeByte[i] = (byte)decValue[i];
DateTime convertedTime = ConvertWindowsDate(timeByte);
textBox7.Text = convertedTime.ToString();
}
public static DateTime ConvertWindowsDate(byte[] bytes)
{
if (bytes.Length != 8) throw new ArgumentException();
return DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0));
}
Related
I wonder what would be the best way to format numbers so that the NumberGroupSeparator would work not only on the integer part to the left of the comma, but also on the fractional part, on the right of the comma.
Math.PI.ToString("###,###,##0.0##,###,###,###") // As documented ..
// ..this doesn't work
3.14159265358979 // result
3.141,592,653,589,79 // desired result
As documented on MSDN the NumberGroupSeparator works only to the left of the comma. I wonder why??
A little clunky, and it won't work for scientific numbers but here is a try:
class Program
{
static void Main(string[] args)
{
var π=Math.PI*10000;
Debug.WriteLine(Display(π));
// 31,415.926,535,897,931,899
}
static string Display(double x)
{
int s=Math.Sign(x);
x=Math.Abs(x);
StringBuilder text=new StringBuilder();
var y=Math.Truncate(x);
text.Append((s*y).ToString("#,#"));
x-=y;
if (x>0)
{
// 15 decimal places is max reasonable precision
y=Math.Truncate(x*Math.Pow(10, 15));
text.Append(".");
text.Append(y.ToString("#,#").TrimEnd('0'));
}
return text.ToString();
}
}
It might be best to work with the string generated by your .ToString():
class Program
{
static string InsertSeparators(string s)
{
string decSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
int separatorPos = s.IndexOf(decSeparator);
if (separatorPos >= 0)
{
string decPart = s.Substring(separatorPos + decSeparator.Length);
// split the string into parts of 3 or less characters
List<String> parts = new List<String>();
for (int i = 0; i < decPart.Length; i += 3)
{
string part = "";
for (int j = 0; (j < 3) && (i + j < decPart.Length); j++)
{
part += decPart[i + j];
}
parts.Add(part);
}
string groupSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator;
s = s.Substring(0, separatorPos) + decSeparator + String.Join(groupSeparator, parts);
}
return s;
}
static void Main(string[] args)
{
for (int n = 0; n < 15; n++)
{
string s = Math.PI.ToString("0." + new string('#', n));
Console.WriteLine(InsertSeparators(s));
}
Console.ReadLine();
}
}
Outputs:
3
3.1
3.14
3.142
3.141,6
3.141,59
3.141,593
3.141,592,7
3.141,592,65
3.141,592,654
3.141,592,653,6
3.141,592,653,59
3.141,592,653,59
3.141,592,653,589,8
3.141,592,653,589,79
OK, not my strong side, but I guess this may be my best bet:
string input = Math.PI.ToString();
string decSeparator = System.Threading.Thread.CurrentThread
.CurrentCulture.NumberFormat.NumberGroupSeparator;
Regex RX = new Regex(#"([0-9]{3})");
string result = RX.Replace(input , #"$1" + decSeparator);
Thanks for listening..
I was trying to convert the datetime to hexadecimal.
This is what I have
string hexValue = DateTime.Today.ToString("X")
I can not find the solution to this.
You can do:
string hexValue = DateTime.Now.Ticks.ToString("X2");
This will give you the hex value.
To convert it back to DateTime you do:
DateTime dateTime = new DateTime(Convert.ToInt64(hexValue, 16));
You can do following with C#.
DateTime dt = new DateTime();
dt = DateTime.Now;
//Convert date time format 20170710041800
string str = dt.ToString("yyyyMMddhhmmss");
//Convert to Long
long decValue = Convert.ToInt64(str);
//Convert to HEX 1245D8F5F7C8
string hexValue = decValue.ToString("X");
//Hex To Long again 20170710041800
long decAgain = Int64.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
Please mark as answer if it is helpfull to you
public static string ConvertStringToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
I have this code but but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.
public static void Main(string[] args)
{
string a =TextFormater("Teste teste ");
Console.WriteLine(a);
}
public static string TextFormater(string ChaineTextArea)
{
string val = string.Empty;
string Valreturn = string.Empty;
int result;
for (int i = 0; i <= ChaineTextArea.Length; i++)
{
val = ChaineTextArea.Substring(i, 1);
var chars = val.ToCharArray();
result = Convert.ToInt32(val);
if (result != 13)
{
Valreturn= val;
}
else
{
Valreturn= "<br>" + val;
}
}
return Valreturn;
}
Your input is not a valid format for converting to Integer. However if you need the ASCII value of those characters, that can be arranged by this
string input = "Teste teste ";
var values = Encoding.ASCII.GetBytes(input);
foreach(var item in values)
{
Console.WriteLine(item);
}
Console.ReadLine();
Hope that will help.
is not valid format I corrected by this code and is working
val = ChaineTextArea.Substring(i, 1);
char []chars = val.ToCharArray();
result = Convert.ToInt32(chars[0]);
I am not sure what you are trying to achieve. If you are trying to convert string to int then it is invalid conversion but you think if the val maybe int or string then try to use int.TryParse
Try it to convert int.Parse(val)
or
Int32.TryParse(val, out number);
I wonder what would be the best way to format numbers so that the NumberGroupSeparator would work not only on the integer part to the left of the comma, but also on the fractional part, on the right of the comma.
Math.PI.ToString("###,###,##0.0##,###,###,###") // As documented ..
// ..this doesn't work
3.14159265358979 // result
3.141,592,653,589,79 // desired result
As documented on MSDN the NumberGroupSeparator works only to the left of the comma. I wonder why??
A little clunky, and it won't work for scientific numbers but here is a try:
class Program
{
static void Main(string[] args)
{
var π=Math.PI*10000;
Debug.WriteLine(Display(π));
// 31,415.926,535,897,931,899
}
static string Display(double x)
{
int s=Math.Sign(x);
x=Math.Abs(x);
StringBuilder text=new StringBuilder();
var y=Math.Truncate(x);
text.Append((s*y).ToString("#,#"));
x-=y;
if (x>0)
{
// 15 decimal places is max reasonable precision
y=Math.Truncate(x*Math.Pow(10, 15));
text.Append(".");
text.Append(y.ToString("#,#").TrimEnd('0'));
}
return text.ToString();
}
}
It might be best to work with the string generated by your .ToString():
class Program
{
static string InsertSeparators(string s)
{
string decSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
int separatorPos = s.IndexOf(decSeparator);
if (separatorPos >= 0)
{
string decPart = s.Substring(separatorPos + decSeparator.Length);
// split the string into parts of 3 or less characters
List<String> parts = new List<String>();
for (int i = 0; i < decPart.Length; i += 3)
{
string part = "";
for (int j = 0; (j < 3) && (i + j < decPart.Length); j++)
{
part += decPart[i + j];
}
parts.Add(part);
}
string groupSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator;
s = s.Substring(0, separatorPos) + decSeparator + String.Join(groupSeparator, parts);
}
return s;
}
static void Main(string[] args)
{
for (int n = 0; n < 15; n++)
{
string s = Math.PI.ToString("0." + new string('#', n));
Console.WriteLine(InsertSeparators(s));
}
Console.ReadLine();
}
}
Outputs:
3
3.1
3.14
3.142
3.141,6
3.141,59
3.141,593
3.141,592,7
3.141,592,65
3.141,592,654
3.141,592,653,6
3.141,592,653,59
3.141,592,653,59
3.141,592,653,589,8
3.141,592,653,589,79
OK, not my strong side, but I guess this may be my best bet:
string input = Math.PI.ToString();
string decSeparator = System.Threading.Thread.CurrentThread
.CurrentCulture.NumberFormat.NumberGroupSeparator;
Regex RX = new Regex(#"([0-9]{3})");
string result = RX.Replace(input , #"$1" + decSeparator);
Thanks for listening..
I am looking to generate a Sequence Number in this format
00000A
00000B
00000B
and so on till
00000Z
and then
00001A
00001B
00001C
...
00001Z
...
00010A
till
99999Z
I know that I can generate Max 2.6 million rows using this method but I guess that is enough
so, if I have the a String, lets say 26522C, Now i want the next number as 26522D
or If I have 34287Z, i want 34288A
I can write the Algorithm about it but there will be lots of parsing of the input string characters by characters
I was wondering is there any easier way of doing it
String GetNextNumberInSequence(String inputString)
{
if (inputString.Length == 6)
{
var charArray = inputString.ToCharArray();
char[] inputChars = { charArray[0], charArray[1], charArray[2],charArray[3],charArray[4],charArray[5] };
if(Char.IsDigit(charArray[5]))
{
//Parse first 5 characters
}
}
}
private static String GetNextNumberInSequence(String inputString)
{
var integerpart = int.Parse(inputString.Substring(0, 5));
var characterPart = inputString[5];
if (characterPart == 'Z')
return string.Format("{0}{1}", (++integerpart).ToString("D5"), "A");
var nextChar = (char)(characterPart + 1);
return string.Format("{0}{1}", (integerpart).ToString("D5"), nextChar.ToString());
}
You can achieve this by converting a number to Base36.
Take a look at this sample:
private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
public static String Base36Encode(long input, char paddingChar, int totalWidth)
{
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray()).PadLeft(totalWidth, paddingChar).ToUpper();
}
and then use it this way:
for(int i = 0; i < 1000; i++)
{
Debug.WriteLine(Base36Encode(i, '0', 6));
}
which will produce this:
000000, 000001, 000002, 000003, 000004, 000005, 000006, 000007, 000008, 000009, 00000A, 00000B, 00000C, 00000D, 00000E, 00000F, 00000G, 00000H, 00000I, 00000J, 00000K, 00000L, 00000M, 00000N, 00000O, 00000P, 00000Q, 00000R, 00000S, 00000T, 00000U, 00000V, 00000W, 00000X, 00000Y, 00000Z, 000010, 000011, 000012, 000013, 000014, 000015, 000016, 000017, 000018, 000019, 00001A, 00001B, 00001C, 00001D, 00001E, 00001F, 00001G, 00001H, 00001I, 00001J, 00001K, 00001L, 00001M, 00001N, 00001O, 00001P, 00001Q, 00001R, 00001S, 00001T, 00001U, 00001V, 00001W, 00001X, 00001Y, 00001Z, 000020, 000021, 000022, 000023, 000024, 000025, 000026, 000027, 000028, 000029, 00002A, 00002B, 00002C, 00002D, 00002E, 00002F, 00002G, 00002H, 00002I, 00002J, 00002K, 00002L, 00002M, 00002N, 00002O, 00002P, 00002Q, 00002R, 00002S, 00002T...
and the positive thing about this approach is that you can convert this back to number by using:
public static Int64 Base36Decode(string input)
{
var reversed = input.ToLower().Reverse();
long result = 0;
int pos = 0;
foreach (char c in reversed)
{
result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
pos++;
}
return result;
}