ulong.Parse(string, NumberStyles) Exception C# - c#

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

Related

how to convert a hex value from a byte array as an interpreted ASCII number into an integer?

I'm just starting with the c# programming and
as the heading describes, I'm looking for a way to convert a number passed to me as an ASCII character in a byte[] to an integer. I often find the way to convert a hex-byte to ASCII-char or string. I also find the other direction, get the hex-byte from a char. Maybe I should still say that I have the values displayed in a texbox for control.
as an example:
hex- code: 30 36 38 31
Ascii string: (0) 6 8 1
Integer (dez) should be: 681
so far I have tried all sorts of things. I also couldn't find it on the Microsoft Visual Studio website. Actually this should be relatively simple. I am sorry for my missing basics in c#.
Putting together this hex-to-string answer and this integer parsing answer, we get the following:
// hex -> byte array -> string
var hexBytes = "30 36 38 31";
var bytes = hexBytes.Split(' ')
.Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
.ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);
// parse string as integer
int x = 0;
if (Int32.TryParse(asciiStr, out x))
{
Console.WriteLine(x); // write to console
}
else
{
Console.WriteLine("{0} is not a valid integer.", asciiStr); // invalid number, write error to console
}
Try it online
A typical solution of the problem is a Linq query. We should
Split initial string into items
Convert each item to int, treating item being hexadecimal. We should subtract '0' since we have not digit itself but its ascii code.
Aggregate items into the final integer
Code:
using System.Linq;
...
string source = "30 36 38 31";
int result = source
.Split(' ')
.Select(item => Convert.ToInt32(item, 16) - '0')
.Aggregate((sum, item) => sum * 10 + item);
If you want to obtain ascii string you can
Split the string
Convert each item into char
Join the chars back to string:
Code:
string source = "30 36 38 31";
string asciiString = string.Join(" ", source
.Split(' ')
.Select(item => (char)Convert.ToInt32(item, 16)));
To convert a byte array containing ASCII codes to an integer:
byte[] data = {0x30, 0x36, 0x38, 0x31};
string str = Encoding.ASCII.GetString(data);
int number = int.Parse(str);
Console.WriteLine(number); // Prints 681
To convert an integer to a 4-byte array containing ASCII codes (only works if the number is <= 9999 of course):
int number = 681;
byte[] data = Encoding.ASCII.GetBytes(number.ToString("D4"));
// data[] now contains 30h, 36h, 38h, 31h
Console.WriteLine(string.Join(", ", data.Select(b => b.ToString("x"))));

Is there a different way to convert to hexadecimal?

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

C# Converting Problems with String Array to Int Array

I`m working with C# and I have a problem at converting a string array to a int array.
First I created a string number with the Console
Console.WriteLine("Geben Sie die Nummer ein:");
string wert = Console.ReadLine();
Then I converted the string to a array
char[] wertarray = wert.ToCharArray();
wertarray1 = new string(wertarray);*
And now comes the problem. I want to convert the string array to a int array, but e.g. for string wertarray1[0]=1, the int array has the value 49.
int wertarray2 = Convert.ToInt16(wertarray1[0]);
Normal the Int value should be 1, but I don`t know where the problem is.
I tried the solutions for "convert a string array to a int array" from this forum, but i still had the problem that the int value get a strange number.
I´m looking forward for help.
Thanks :-).
Convert.ToInt16(Char) takes the numeric value of the char (i.e. its Unicode code-point value) and returns that number. While you might think Convert.ToInt16('1') should return 1, consider what would happen if you tried Convert.ToInt16('#') for example.
Use Int16.Parse (or TryParse) to actually parse a string to numbers. As you're working with individual characters to represent 0-9 you might as well do it using simple arithmetic without the need to call any Parse function:
String line = Console.ReadLine();
List<Int16> numbers = new List<Int16>( line.Length );
foreach(Char c in line) {
Int16 charValue = (Int16)c;
if( charValue < 48 || charValue > 57 ) throw new Exception("char is not a digit");
Int16 value = charValue - 48;
numbers.Add( value );
}
Answers provided already explain your problem and provide solution too.
In general, you can convert the char to string and parse them to integer (not the best performance though).
If you have all numeric string
var numStr = "136";
var numbers = numStr.Select(n => int.Parse(n.ToString())).ToList(); // {1, 3, 6}
If your string contains non numbers too
var mixStr = "1.k78Tj_n";
int temp;
var numbers2 = new List<int>();
mixStr.ToList().ForEach(n =>
{
if (int.TryParse(n.ToString(), out temp))
numbers2.Add(temp);
}); //{ 1, 7, 8 }
You're getting the Unicode code point value of the characters in your input stream -- 49 is the unicode value for the character 1.
If you want to convert a unicode character that is a digit to the numeric value of that digit, you can use System.Globalization.CharUnicodeInfo.GetDecimalDigitValue(char c):
var wertarray2 = wert.Select(c => (short)CharUnicodeInfo.GetDecimalDigitValue(c)).ToArray();
This handles all digits (including superscripted numbers) not just the standard ASCII digits.

WP8 - C# - Parsing string to decimal FormatException

I am currently trying to parse a string, "277.968", to decimal, but I am getting a FormatException exception.
I have read that I need to perform the decimal parse this way:
string str = "277.968";
decimal.Parse(str, CultureInfo.InvariantCulture);
Still, I am getting the said exception.
What could I do?
EDIT: Fixed float to decimal
Printing the lenght of the string, it reported it being 80 chars long.
Right, well that's the problem then. Your string isn't "277.968" - it's "277.968\0\0\0\0\0\0(...)" - and that can't be parsed.
My guess is that you've read this from a TextReader of some kind, but ignored the return value of Read, which is the number of characters that have been read.
So for example, if your current code is effectively:
char[] risul = new char[80];
reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul), CultureInfo.InvariantCulture);
then you should instead have:
char[] risul = new char[80];
int charsRead = reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul, 0, charsRead),
CultureInfo.InvariantCulture);
... although that's still assuming that you're reading all of the appropriate data in a single call to Read, which isn't necessarily the case. You may well just want:
string data = reader.ReadToEnd();
decimal value = decimal.Parse(data, CultureInfo.InvariantCulture);

How do I convert a set of hexadecimal bytes to a custom string

So basically I need to find a way to convert this; 29 38 33 30 3D 34 FF, to this; Zidane
FF being character to imply end of name.
What I've got so far is that I can read that to its literal string, )830=4ÿ, which isn't at all user friendly for what I'm trying to create.
Now just by that one name alone you can guess what I'm working on, but this is the only thing I seem to be getting stuck on is the whole custom character string.
This is the code to get string from hex string,
private string HexString2Ascii(string hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
Will be happy if you explain in what format is the input string, hex or byte array.
Ah I see what is happening. Remember that when using Hex you have Unicode, Shift JIs and in your case Little-endian. As I understand it looks like you have an incorrect hex table for what you are currently trying to read. Sorry if my answer didn't help enough.
If you decode the hex values and expect the output to be ascii encoded then you get exactly what you state above, as seen using this online hex decoder.
The string is not obviously ascii encoded. I cant be certain of the exact encoding but by looking at the values, the expected output and the difference between the values you can predict how to map values to letters:
A-Z = 0x04 - 0x29
EG: 'A' = 04, 'B' = 05, .... 'Z' = 29
a-z = 0x30 - 0x55
EG: 'a' = 30, 'b' = 31, .... 'z' = 55
This should be enough to get you a readable string.

Categories