I have an array of strings that are in hex format, for example {"3d", "20", "5a"}.
What would be a good way of converting each element of this string to decimal format?
I've tried using GetBytes(), but that doesn't seem to work since it sees "3d" as two different characters because it doesn't know that it is in hex format.
GetBytes() works fine in a situation like below but not if characters are in hex.
What am I missing here?
string a = "T";
byte[] b = {10};
b = System.Text.UTF8Encoding.Default.GetBytes(a);
Use int.Parse with NumberStyles.HexNumber.
int decValue = int.Parse(hexValue,System.Globalization.NumberStyles.HexNumber);
Try that.
HexValue is the number in hex format and decValue is in decimal...
Related
I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "
The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.
string TextToConvert = "Test Andrei";
TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);
List<char> Chars = TextToConvert.ToCharArray().ToList();
string CharValue = "";
string secondHexConvert = "";
foreach(char c in Chars)
{
CharValue+=Convert.ToInt32(c);
secondHexConvert+=Convert.ToString(c, 16)+" ";
}
string hexValue = String.Format("{0:X}", CharValue)+" ";
I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"
To convert such a big integer to a hexadecimal string, use the aptly named BigInteger type:
var num = BigInteger.Parse("841011151163265110100114101105");
string hex = num.ToString("X");
Console.WriteLine(hex);
will output:
0A9D741E82C98FC6A137B75371
but here's a snag, the output you showed in your question is somewhat different, let me show it together with what the code above produces:
0A9D741E82C98FC6A137B75371
a9d741e82c990000000000000
As you can see, the numbers start the same but your example then ends up with lots of zeroes.
The only way I understand this could happen is that they're in fact not using a type that can hold that many significant digits, so you get a rounding error.
Many of the dynamic programming languages allows you to use floating point numbers and integers interchangeably, I guess this is what happened, a floating point type that can only hold 17-18 significant digits or some such was used, and you lost precision. .NET, however, doesn't have built-in support for converting floating point types to hexadecimal.
You can see that .NET produces the exact value by converting back:
Console.WriteLine(BigInteger.Parse(hex, System.Globalization.NumberStyles.HexNumber));
outputs:
841011151163265110100114101105
In other words, I'm not sure you can get the exact same results in .NET.
Corollary: Don't use that site for this kind of conversion!
You can use the following code to convert a string to hexadecimal:
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
And you just call it using:
string testString = "11111111";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
Can anyone help me on how to convert decimal to ASCII using C#.net?
When I input a decimal into the textbox1, after clicking the CONVERT button then the result will display in textbox2. My problem is the code on how to convert decimal to ASCII. How to do this?
Here is a simple solution I found on the net. See if it works for you. 65 being the ASCII character.
char c = Convert.ToChar(65);
string d = c.ToString();
Source: http://forums.asp.net/t/1827433.aspx?Converting+decimal+value+to+equivalent+ASCII+character+in+c+
Another source: Decimal to ASCII Convertion
Is ASCII a requirement? Normally UTF-8 should be used when sending a string to another app.
var utf8 = Encoding.Utf8.GetBytes(myDecimal.ToString());
However, if you just want to convert a decimal to a string do
var s = myDecimal.ToString();
For example you have a Textbox and a Button
Textbox name is txtInput.
//Converting Decimal to ASCII
MessageBox.Show(Convert.ToChar(Convert.ToByte( txtInput.Text )).ToString());
//Convertşng ASCII to Decimal
MessageBox.Show(Convert.ToByte(Convert.ToChar( txtInput.Text )).ToString());
i been working on this "string to Binary" method for longer than usual and i have no idea where i m going wrong.
i have already searched the internet for solution but nothing seem to be working the way it supposed to do.
public static string hexToBin(string strValue)
{
byte[] hexThis = ASCIIEncoding.ASCII.GetBytes(strValue.ToString());
string thiI = ToHex(strValue);
ulong number = UInt64.Parse(*string*, System.Globalization.NumberStyles.HexNumber);
byte[] bytes = BitConverter.GetBytes(number);
string binaryString = string.Empty;
foreach (byte singleByte in bytes)
{
binaryString += Convert.ToString(singleByte, 2);
}
return binaryString;
}
ToHex(string) takes string and returns its hex representation.
but all i keep getting is "Input string was not in a correct format." at the ulong.Parse(string, NumberStyle); and no matter what are my inputs i keep getting the "FormatException" "Input string was not in a correct format." Error.
the inputs and its outputs
string: format exception - "Hello"
hex: format exception - "48 65 6C 6C 6F"
byte[]: format exception - { 72, 101, 108, 108, 111 }
i have also tried using the "Hello" string, but it threw me the same error.
would you please let me know what i m doing wrong in here?
i also have tried "Clean/build/rebuild" restart visual studio, but i keep getting the same format exception.
EDIT,, used UInt64.Parse() not ulong.Parse() and the used string is "Hello" w/o quotation.
EDIT #2,,
so i did this based on knittl suggestion and used the Convert.ToUInt64 instead of the parse, but still getting same error
ulong binary;
string binThis;
byte[] ByteThis;
binThis = "Hello";
ByteThis = ASCIIEncoding.ASCII.GetBytes(binThis);
binary = Convert.ToUInt64(ByteThis);
Console.WriteLine(binary);
the CurrentCulture is set to en-US and i m also using en-US keyboard
EDIT #3 - Solved
thanks to knittl
the solution is as follow:
string thestring = "example";
string[] finale = new string[thestring.Length];
foreach (var c in ByteThis)
{
for (int i = 0; i < ByteThis.Length; i++)
{
thestring = Convert.ToString(c, 2);
thestring = "0" + thestring;
if (thestring.Length == 9)
thestring.Remove(0, 1);
finale[i] = thestring;
Console.WriteLine(finale[i]);
}
}
the final for is to check on the solution.
this question aimed to get the binary representation of a given string.
Not totally clear, what your method should do (i.e. what format the input string is. Is it a bas10 number, or already a hexadecimal number?)
If it's a hexadecimal number, use ulong.Parse(inputStr, NumberStyles.HexNumber). If not, simply use ulong.Parse(inputStr). Note that NumberStyles.HexNumber does not allow the 0x prefix (Convert.ToUInt64(inputStr) does however).
Then, once you have your input string parsed to a number, simply use Convert.ToString(number, 2) to convert to base2. You will notice that there is no overload which takes an ulong and an int, but you can simply cast your number to a (signed) long, since the binary representation will be identical between the two (cf. two's complement). So, in effect Convert.ToString((long)number, 2).
No need for complicated loops and conversions to byte arrays.
Bonus answer.
If you are not too concerned with performance, you can even use a LINQ one-liner:
Encoding.ASCII.GetBytes(inputStr).Aggregate(
new StringBuilder(),
(sb, ch) => sb.Append(Convert.ToString(ch, 2).PadLeft(8, '0')),
sb => sb.ToString());
i am using convert.tobyte to convert string to byte. the problem is if the data is:
string data = "5";
byte b = Convert.tobyte(data); works fine.
but, if
string data = "S"
byte b = Convert.tobyte(data); DOESN'T WORK!
ERROR : Input string was not in a correct format
What is wrong and how to solve it?
Note: i am extracting a values from textbox, so the conversion works only if the input is number digits, not characters.
how to include the characters?
Thanks.
This is exactly how Convert.ToByte method works http://msdn.microsoft.com/en-us/library/y57wwkzk.aspx
Only digits in string accepted.
Did you meant converting the string to byte array? If so, use:
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(yourString);
For strings containing only ASCII characters, the size of array will be equal to length of your string and every byte in array will be an ord value for the character. If string contains multibyte characters the size of array will be greater than length of string.
When you are not sure if a variable of string type could be correctly converted to a number you need to use the TryParse family of methods like Byte.TryParse method
string data = "S";
byte b;
if(byte.TryParse(data, out b))
Console.Writeline("Worked: " + b.ToString());
The TryParse has the advantage to not throw an exception if the string cannot be converted to a number and return just false or true while the out parameter is filled with the converted value if possible.
I've spent the better part of a week and finally figured out how to convert packed data from the mainframe into a hexadecimal number representation. Now, I am trying to figure out how to get that hexadecimal string into an integer in Visual C#. I'm sure there's an easy function for this, but it's bypassing my searches at the moment. Here's the code that is giving me the mainframe representation:
// Get the packed decimal field from the input record
String testString = dataRecord.Substring(40, 4);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(testString);
// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding ebcdic = Encoding.GetEncoding("IBM037");
// Unpack Data
Byte[] bt = Encoding.Convert(ascii, ebcdic, bytes);
// Get the data into a string in the format of 00-5F (represents a positive 5)
// The format of 00-5D (represents a negative 5)
String numberString = BitConverter.ToString(bt);
If the mainframe decimal value is 5, bt[0] ends up being 00, and bt[1] ends up being 5F. After converting to a string, I end up with "00-5F". What I really want to have, is an integer or string that just says "5". I could just write my own thing to test every digit, and return the correct value, but I'm thinking there has to be a way to convert from a hexidecimal signed number to a string or integer without having to write a routine of my own. Does anyone have any ideas what the function might be? I've tried the standard convert.toint, todecimal, etc. functions but they get freaked out by this format.
Thanks!