How do i convert hexadecimal value from string to int? - c#

I have a string which typically is in the format : "0xFF".
I'll trim it since there is a chance of whitespace.
How do i convert that into hex and convert "34" to decimal?
I know about .Parse but does this support hex characters when the string is "0x123"?

You'll have to strip the "0x" part, but this snippet works:
using System;
using System.Globalization;
public class StrToInt {
public static void Main(string[] args) {
string val = "FF";
int num = Int32.Parse(val, NumberStyles.AllowHexSpecifier);
Console.WriteLine(num);
}
}

int i = int.Parse( "FF", System.Globalization.NumberStyles.HexNumber );
MessageBox.Show( i.ToString() ); // displays 255
However, you will need to trim the leading "0x".

Related

turning a string with binary into binary in C#

lets say I have a string that contains binary, like this:
string test = "01001010";
so I want to do something like this:
someFunc(test);
and this function would return exactly what the test variable says, but in byte form instead of string.
example:
using System;
class Program
{
static void Main()
{
Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
}
}
this program prompts you to enter a byte using Console.ReadLine (which returns a string), turns it into a byte, then turns it into a char.
How could I do this?
You could write it in this way:
using System;
class Program
{
static byte someFunc(string text)
{
byte t = 0;
for (int i = 0; i < 8; i++)
t = (byte)(t * 2 + (text[i] - '0'));
return t;
}
static void Main()
{
Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
}
}
But it would be useful before using someFunc() to check if string is not okey (for example, that there would be shown an error message if input is "10102010")
Use Convert.ToInt32(string, int) where string is the string you want to convert, and int is the base of the number system you want to convert from, in your case base 2 or binary. Or if you really desperately need it to be a byte, then you can use Convert.ToByte(string, int). Like so:
using System;
class Program
{
public static void Main()
{
var input = Console.ReadLine(); // 01001010
var number = Convert.ToInt32(input, 2);
Console.WriteLine(number); // prints '74'
}
}
Be warned that Convert.ToXyz() will throw an exception of type FormatException if the given input string contains character that are illegal for the given base. For base 2 that would be any character that's not a 0 or 1, you might want to catch such exceptions, or check that all characters in the input string are either a '0' or '1' beforehand
Edited:
Take char after char, add it to result byte and multiply by 2 to convert from binary to decimal (except for the last char, it should be just added).
Then return byte as char.
public static char someFunc(string bs) {
byte result = 0;
for (int i = 0; i < bs.Length - 1; i++)
{
if (bs[i].Equals('1'))
{
result += 1;
}
result *= 2;
}
if (bs[bs.Length - 1].Equals('1'))
{
result++;
}
return (char) result;
}
returns J for "01001010"
Hi this is one implementation which i use in java, but this will ork for c# as well. My be you need some syntax changes.
static int someFunc(String s){
int binary = 0x00;
for(int i=0;i<8;i++){
if(s.charAt(i) == '1')
binary =(binary<<1) | 0x01;
else if(s.charAt(i) == '0')
binary =(binary<<1) | 0x00;
}
return binary;
}

How to correctly convert letters to numbers?

I have a string which comprise lots of letters. I have used the following code to convert it to numbers, but the new string t still gives me imperfect result.
For example:
tung2003 -> -1-1-1-12003
What I expected: 1161171101032003 (116 is the ASCII code of t, 117 is the ASCII code of u
string t=null;
foreach (char c in Properties.Settings.Default.password)
{
int ascii = (int)Char.GetNumericValue(c);
int counter=0;
counter = ascii;
t = t + Convert.ToString(counter);
}
The problem is the - character. I want my new string only comprises numbers.
It looks like you do not want the ASCII values of the numbers based on your expected output. In that case you can just do something like this:
string input = "tung2003";
string output = string.Empty;
foreach(char c in input)
{
if(char.IsNumber(c))
{
output += c;
}
else
{
output += ((byte)c).ToString();
}
}
//output is now: 1161171101032003
Fiddle here
Also added as a Linq expression for a short hand solution.
// Method 1 Linq
string output = string.Concat(("tung2003".ToCharArray()
.Select(s=> char.IsDigit(s) ? s.ToString() : ((int)s).ToString())));
// Method 2
string input = "tung2003";
string output = string.Empty;
foreach (char c in input)
{
if (Char.IsDigit(c)) output += c.ToString();
else output += ((int)c).ToString();
}
Extrapolating your output it looks like you want two different things. You want to tally each ascii character as long as it is a letter and extract the numeric values to append. The following provides three options, the first is to tally the ascii values from letters and the other two are ways to extract only digits. Because your code example uses a Password I am assuming you are trying to do some sort of custom hashing and if that is the case you should use a Hash implementation from the Cryptography namespace or some other package.
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var combined = OnlyLettersToAscii("tung2003") + OnlyNumbers("tung2003");
Console.WriteLine($"Input: tung2003 Output: {OnlyNumbers("tung2003")}");
Console.WriteLine($"Input: tung2003 Output Regex: {OnlyNumbersWithRegex("tung2003")}");
Console.ReadKey();
}
private static string OnlyLettersToAscii(string originalString)
{
if (string.IsNullOrWhiteSpace(originalString)) return originalString;
return string.Join(string.Empty, originalString.ToArray()
.Where(w => char.IsLetter(w))
.Select(s => ((int)s).ToString()));
}
private static string OnlyNumbers(string originalString)
{
if (string.IsNullOrWhiteSpace(originalString)) return originalString;
return new string(originalString.Where(w => char.IsDigit(w)).ToArray());
}
public static string OnlyNumbersWithRegex(string originalString)
{
return Regex.Replace(originalString, #"[^\d]", string.Empty);
}
}
}
string t = "";
foreach (char c in Properties.Settings.Default.password)
{
if (IsNumber(x)) t += System.Convert.ToInt32(c).ToString();
else
{
t += c.ToString();
}
}
Moreover, if you just want to get rid off '-' the use this code: t =String.Replace(t, '-');

How to remove first two characters from a date string (MM/dd/yyyy) in array?

I have an array that stores date input from users but I want to remove or trim the first two characters (basically, I want to remove the month) from every date inputted in the array:
class MainClass
{
{
//Main Program....
}
public static int GetInput (string[] date)
{
int loop;
(for int i=0 ; i < loop ; i++)
dArray[i] = Console.ReadLine();
}
}
class OtherClass
{
//Required data properties, etc...
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
// How would I code the rest of this function so that it removes the first 2 characters from "MM/dd/yyyy".
//Keep in mind I have also allowed users to input the date in formats like
//"M/dd/yyyy" (such as 3/07/2011 vs 03/07/2011)
//so sometimes I would only need to remove ONE NOT TWO of the month character //
}
}
With string, you can use a simple substring:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var indexOfFirstBar = dateInput.IndexOf('/');
var start = indexOfFirstBar + 1;
return dateInput.Substring(start, dateInput.Length - start);
}
But I suggest you to convert to DateTime and use the date format you want:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var date = Convert.ToDateTime(dateInput);
return date.ToString("dd/yyyy"); // Use the format you want here
}
About Convert.ToDateTime and date formats.
Something like this?
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
return monthNumberRemoved[1] + "/" + monthNumberRemoved[2];
}

C# Writing Binary Data

I am trying to get some data to write to a binary file. The data consists of multiple values (strings, decimal, ints) that need to be a single string and then written to a binary file.
What I have so far creates the file, but it's putting my string in there as they appear and not converting them to binary, which I assume should look like 1010001010 etc. when I open the file in notepad?
The actual output is Jesse23023130123456789.54321 instead of the binary digits.
Where have I steered myself wrong on this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace BinaryData
{
class Program
{
static void Main(string[] args)
{
string name = "Jesse";
int courseNum = 230;
int num = 23130;
decimal d = 123456789.54321M;
string combined = name + courseNum + num + d;
FileStream writeStream;
writeStream = new FileStream("BinaryData.dat", FileMode.Create);
BinaryWriter bw = new BinaryWriter(writeStream);
bw.Write(combined);
}
}
}
There's more than one way to do this, but here's a basic approach. After you combine everything into a single string iterate through the string and convert each character into it's binary representation with Convert.ToString(char, 2). ASCII characters normally will be 7 bits or less in length, so you'll need to PadLeft(8, '0') to ensure 8 bits per byte. Then for the reverse you just grab 8 bits at a time and convert it back to its ASCII character. Without padding with leading 0's to ensure eight bits you won't be sure how many bits make up each character in the file.
using System;
using System.Text;
public class Program
{
public static void Main()
{
string name = "Jesse";
int courseNum = 230;
int num = 23130;
decimal d = 123456789.54321M;
string combined = name + courseNum + num + d;
// Translate ASCII to binary
StringBuilder sb = new StringBuilder();
foreach (char c in combined)
{
sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
}
string binary = sb.ToString();
Console.WriteLine(binary);
// Translate binary to ASCII
StringBuilder decodedBinary = new StringBuilder();
for (int i = 0; i < binary.Length; i += 8)
{
decodedBinary.Append(Convert.ToChar(Convert.ToByte(binary.Substring(i, 8), 2)));
}
Console.WriteLine(decodedBinary);
}
}
Results:
01001010011001010111001101110011011001010011001000110011001100000011001000110011001100010011001100110000001100010011001000110011001101000011010100110110001101110011100000111001001011100011010100110100001100110011001000110001
Jesse23023130123456789.54321
Fiddle Demo
Here you go:
The main method:
static void Main(string[] args)
{
string name = "Jesse";
int courseNum = 230;
int num = 23130;
decimal d = 123456789.54321M;
string combined = name + courseNum + num + d;
string bitString = GetBits(combined);
System.IO.File.WriteAllText(#"your_full_path_with_exiting_text_file", bitString);
Console.ReadLine();
}
The method returns the bits, 0 and 1 based on your string input of-course:
public static string GetBits(string input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in Encoding.Unicode.GetBytes(input))
{
sb.Append(Convert.ToString(b, 2));
}
return sb.ToString();
}
If you want to create the .txt file then add the code for it. This example has already a .txt created, so it just needs the full path to write to it.

How to convert a map point string to double?

I have a string such as 45,5235234096284 or 112,013574120648. I want to convert it to double. I have tried following code but i got error 'System.Globalization.CultureInfo' does not contain a definition for 'GetCultureInfo
' because of framework version. I'm not able to change framework option.I have looked some another solution but i couldn't understand clearly.What is the best way converting these string to double with their commas.
var convertedMapPoint = double.Parse(mapPoint, CultureInfo.GetCultureInfo(1053));
First, you should split your input on spaces, since that is the separator:
string input = "45,5235234096284 112,013574120648";
string[] splitted = input.Split(' ');
Then you can iterate over the result of the splitting, and convert each to a double:
List<double> doubles = new List<double>();
foreach (string s in splitted)
{
doubles.Add(double.Parse(s, new CultureInfo("fr-FR")));
}
I used fr-fr, since it has a comma as decimal separator, but you can use any culture that does that.
If that doesn't work for you, and you are 100% sure there is no . as thousand separator, you can use this:
doubles.Add(double.Parse(s.Replace(",", ".")));
Then you might want to add the invariant culture to be platform independent:
doubles.Add(double.Parse(s.Replace(",", ".", CultureInfo.InvariantCulture)));
You should split the string into array delimited by Space, and than convert each part.
string mapPoint = "45,5235234096284 112,013574120648";
var mapPoints = mapPoint.Split(' ');
var convertedMapPointX = double.Parse(mapPoints[0], CultureInfo.GetCultureInfo(1053));
var convertedMapPointY = double.Parse(mapPoints[1], CultureInfo.GetCultureInfo(1053));
Console.WriteLine("X: {0}\tY: {1}", convertedMapPointX, convertedMapPointY);
Output:
X: 45.5235234096284 Y: 112.013574120648
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringToMapPoint
{
class Program
{
static void Main(string[] args)
{
string mapPointStr = "45,5235234096284 112,013574120648";
MapPoint mp = mapPointStr.ToMapPoint();
Console.WriteLine(mp.ToString());
}
}
public class MapPoint
{
public double X { get; set; }
public double Y { get; set; }
public override string ToString()
{
return "X: " + X + " Y: " + Y;
}
}
public static class MapPointHelper
{
public static MapPoint ToMapPoint(this string str)
{
var split = str.Replace(".", ",").Split(' ');
return new MapPoint() { X = Double.Parse(split[0]), Y = Double.Parse(split[1]) };
}
}
}

Categories

Resources