Convert hexadecimal string to an integer - c#

int value = Convert.ToInt32('o');
Byte[] b = new Byte[] { ( byte)value };
File.WriteAllBytes(Default.ProjectsPath , b);
when I open the file it displays o, I want to write the byte value to the file?

Remove the0x then convert:
int i = Convert.ToInt32("0xFE".Substring(2), 16);

Convert.ToInt16(string) will not be able to convert strings that start with '0x', even though that's the correct notation for base 16 numbers. If you want to use your solution, you will need to remove the "0x" from the string conversion. Replace
string s=String.Format("0x{0:X}", value);
with
string s=String.Format("{0:x}", value);
Or you can use Alex K.'s idea and replace
int x=Convert.ToInt16(s);
with
int x=Convert.ToInt16(s.Substring(2));

if you are the one producing the string in the first place then like Alex Barac suggested, dont place a 0x prefix at all... (why create problems you dont need)
if you have to have the prefix, use it... if the prefix is '0x' use
int i = Convert.ToInt32("0xFE".Substring(2), 16); as Alex K. suggested
if it is not '0x', then it probobally a Base10 number:
int i = Convert.ToInt32("342", 10);

Related

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.

ulong.Parse(string, NumberStyles) Exception 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());

hex to bin converter

I have a textbox which takes as input hex values and a messagebox which shows the output in binary. For example:
input : F710(string)
output : 1111011100010000
I will use that value in another work. How could I do this?
I am not really sure if I understand your question, but the easiest thing that comes to mind is to just calculate the values on the fly. For example:
public static string BitStringFromHexString(string hex)
{
int i;
if (!Int32.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out i))
{
throw new ArgumentException(String.Format("Input not recognized '{0}'. ", hex), "hex");
}
return Convert.ToString(i,2);
}
string binV = "";
binV = Convert.ToString(Convert.ToInt32(textBox1.Text, 16), 2);
textBox2.Text=binV;
Should do the job for ya.

Formatting values

Hi i have a int example as 3 i need to format it as 003 . is the only way is convert to a string and concat and convert back ?
I guess this is what you want:
int n = 3;
string formatted = n.ToString("000");
Alternatively:
string formatted = String.Format("{0:000}", n);
More info here.
You can apply the .ToString("000"); method.
Debug.WriteLine(3.ToString("000"));
You can parse the resulting string value by using int.Parse or int.TryParse:
Debug.WriteLine(int.Parse("003"));
See Custom Numeric Format Strings
If it's an int object, the leading zeros will always be removed, regardless if you convert it to a string and back.
use the pad functionint i = 1;
i.ToString().PadLeft(3, '0');

Copy first few strings separated by a symbol in c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Categories