How to convert Datetime to hexadecimal - c#

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;
}

Related

How to create qr code in tlv (tag, length, value) format in c# windows application

i want to create a qr code with five tlv data.
Sellers name
Vat number
Datetime
Invoice total
Vat amount
I need this for vat bill of Saudi arabia. I want to implement this in five steps
Create tlv data
Convert to hex representation
Convert to string
Convert to base64 string
Create qr code bitmap image.
Any helps will be appreciated
Hi We have completed and created a DEMO program to understand ( I am using c# for my demonstration)
See my Code and you should understand
1 ) Define the function to convert each TAG to hex bypassing the Tag No and TAG Value and returning the HEX Value
public static String text2hex(Int32 Tagnum, String TagVal)
{
string hexval = text2hex(TagVal);
string hextag = decToHexa(Tagnum);
string hexlen = decToHexa(TagVal.Length);
return (hextag + hexlen + hexval);
}
2 ) Define a function to pass the HEX value and return a BASE64 Encoded Value
public static String HexToBase64(string strInput)
{
var bytes = new byte[strInput.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
}
return Convert.ToBase64String(bytes);
}
3 ) convert all tags and tag values and concatenate them (TLV Format)
string Hexcode = text2hex(1, CompName) + text2hex(2, Vatno) + text2hex(3, datetimetax) + text2hex(4, amountTotal) + text2hex(5, amountVat);
once you have the HEXcode of the value joined convert them to base64
string HextoBase = Base64StringEncode(Hexcode)
Convert the Base64 to QR Code
Reference Document
enter image description here
Found the issue for the Arabic. The Length for Latin text is the same in regular and utf8 mode, however for arabic, it will be different. so when producing the TLV, the L should be the length of the text after conversion to UTF8. So improving the answer above to:
public static String GetTLV(Int32 Tagnum, String TagVal)
{
return GetTLV(Tagnum, Encoding.UTF8.GetBytes(TagVal).Length, TagVal);
}
public static String GetTLV(Int32 Tagnum, int TagLen, String TagVal)
{
string hexval = text2hex(TagVal);
string hextag = decToHexa(Tagnum);
string hexlen = decToHexa(TagLen);
return (hextag + hexlen + hexval);
}
private static string text2hex(string tagVal)
{
byte[] ba = Encoding.UTF8.GetBytes(tagVal);
return BitConverter.ToString(ba).Replace("-","");
}
private static string decToHexa(int tagnum)
{
return tagnum.ToString("X2").Replace("-", "");
}

Faking decimal with string format

I currently have the following longs in a small C# program.
long one = 1;
long two = 1005;
long three = 100000005;
long four = 1111112258552;
I want to format them in a string so that they are a thousandth of the size without dividing the values by a thousand.
Example
Input : Output
1 0.001
1005 1.005
100000005 100000.005
1111112258552 1111112258.552
I have tried string formats such as {0:0,000} and {0:0.000} but neither provided the result I was after.
How can I achieve the result I am after? Any tips or pointers would be appreciated
Some sample code
long one = 1;
long two = 1005;
long three = 100000005;
long four = 1111112258552;
string format = "{0:0,000}";
string s1 = String.Format(format, one);
string s2 = String.Format(format, two);
string s3 = String.Format(format, three);
string s4 = String.Format(format, four);
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
Console.WriteLine(s4);
Try "{0:0,.000}" for your format.
long one = 1;
long two = 1005;
long three = 100000005;
long four = 1111112258552;
string format = "{0:0,.000}";
string s1 = String.Format(format, one);
string s2 = String.Format(format, two);
string s3 = String.Format(format, three);
string s4 = String.Format(format, four);
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
Console.WriteLine(s4);
Console output:
0.001
1.005
100000.005
1111112258.552
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--custom-specifier-2

exception Convert ToInt32 dans c#

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);

How to convert HEX to Datetime in c#

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));
}

How do I decode a base64 encoded string?

I am trying to "decode" this following Base64 string:
OBFZDTcPCxlCKhdXCQ0kMQhKPh9uIgYIAQxALBtZAwUeOzcdcUEeW0dMO1kbPElWCV1ISFFKZ0kdWFlLAURPZhEFQVseXVtPOUUICVhMAzcfZ14AVEdIVVgfAUIBWVpOUlAeaUVMXFlKIy9rGUN0VF08Oz1POxFfTCcVFw1LMQNbBQYWAQ==
This is what I know about the string itself:
The original string is first passed through the following code:
private static string m000493(string p0, string p1)
{
StringBuilder builder = new StringBuilder(p0);
StringBuilder builder2 = new StringBuilder(p1);
StringBuilder builder3 = new StringBuilder(p0.Length);
int num = 0;
Label_0084:
while (num < builder.Length)
{
int num2 = 0;
while (num2 < p1.Length)
{
if ((num == builder.Length) || (num2 == builder2.Length))
{
MessageBox.Show("EH?");
goto Label_0084;
}
char ch = builder[num];
char ch2 = builder2[num2];
ch = (char)(ch ^ ch2);
builder3.Append(ch);
num2++;
num++;
}
}
return m0001cd(builder3.ToString());
}
The p1 part in the code is supposed to be the string "_p0lizei.".
It is then converted to a Base64 string by the following code:
private static string m0001cd(string p0)
{
string str2;
try
{
byte[] buffer = new byte[p0.Length];
str2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(p0));
}
catch (Exception exception)
{
throw new Exception("Error in base64Encode" + exception.Message);
}
return str2;
}
The question is, how do I decode the Base64 string so that I can find out what the original string is?
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encoding and decoding the text. All you have to do is reverse m0001cd:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.
// Decode a Base64 string to a string
public static string DecodeBase64(string value)
{
if(string.IsNullOrEmpty(value))
return string.Empty;
var valueBytes = System.Convert.FromBase64String(value);
return System.Text.Encoding.UTF8.GetString(valueBytes);
}

Categories