Char to Int explicit Conversion in C# [duplicate] - c#

This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 9 months ago.
I was trying to learn explicit conversion in c#.
First I explicitly converted string to int
namespace MyfirstCSharpCode
{
class Program
{
static void Main(string[] args)
{
string str = "1234";
int i = Convert.ToInt16(str);
Console.WriteLine(i);
}
}
}
it worked and the result is : 1234
Now I tried to convert char to int
namespace MyfirstCSharpCode
{
class Program
{
static void Main(string[] args)
{
char str = '1';
int i = Convert.ToInt16(str);
Console.WriteLine(i);
}
}
}
And now the result is 49, the ASCII value of 1. How to get the char 1 instead of ASCII value. Please don't be too harsh its my first day in c# ;)..

You hit the overload methods of Conver.ToInt16(char) , and char is a UTF-16 code unit and representing 1 is 49. You can use Int16.TryParse to safe parse the number (need in 16 bit sign number) in order to get the valid integer.
string str = "1"; // use string if your number e.g 122
short number; // convert to 16 bit signed integer equivalent.
if (Int16.TryParse(str, out number))
{
Console.WriteLine(number);
}

Related

Working with Decimals and Integers [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 5 years ago.
I'm sure this is a stupid question but I'm a newbie!
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var myInt = ((1000/2048) * 1536);
Console.WriteLine(myInt);
}
}
}
Output is:
0
Can someone tell me how to get the correct number (750)?
By default, 1000 and 2048 are int, therefore the result will be treated as an int.
You have to cast them to double.
Option 1:
var myInt = (((double)1000 / 2048) * 1536);
Console.WriteLine(myInt);
Option 2:
var myInt = ((1000.0 / 2048) * 1536);
Console.WriteLine(myInt);
You should read about value types in C#:
https://www.tutorialspoint.com/csharp/csharp_data_types.htm
https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx

Print hexadecimal code from int into string

I need to save a string with the hexadecimal code of an int.
For example the hexadecimal value for the int 15 is xoooF.
My problem is that I have to save this code in a string like this:
int myint = myStringLength; //this value might change
string myIntExhCode = myint.convertThisIntoMyCode();
//and the string has to be exactly "/xoooF"
So in this question I have two problmes:
The first is how to automatically convert an int into the hexadecimal code like 15 = xoooF
The second is how to create a string containing \xoooF because any try of concatenating strings like this resulted into a \\xoooF and this is not correct since in output I need the string to be converted into the ascii code.
How can I achieve those two tasks?
Any help will be appreciated
Your question is quite vague. If you want hexadecimal format, but with 0 (digit zero) changed into o (small latin letter o) you can implement, say, an extension method (in order to keep your proposed code intact):
public static partial class IntExtensions {
public static string convertThisIntoMyCode(this int value) {
return "\\x" + value.ToString("X4").Replace('0', 'o'); // or "/x" + ...
}
}
...
int myint = myStringLength; //this value might change
string myIntExhCode = myint.convertThisIntoMyCode();
// Test output
Console.Write(myIntExhCode);
How about
int i = 15;
string result = "\\x" + i.ToString("X").PadLeft(4, 'o');

How to know what user entered in C# [duplicate]

This question already has answers here:
C# testing to see if a string is an integer?
(10 answers)
Closed 6 years ago.
For Ex:
cw("enter anything");
//we dont know if user entered int or string or any other datatype so we would check as,
if(userEntered == int){}
if(userEntered==string){}
In other way: If user enters for example int value so we convert it and save it but if we dont know what user entered, how will we judge or detect?
For a console application taking in user input, assume its a string to begin with as string will be able to hold whatever the input is.
If needed, then you can parse it to another datatype such as ints or floats.
public class MainClass
{
public static void Main(string[] args)
{
String value = Console.ReadLine();
var a = new MainClass();
if a.IsNumeric(value){
//your logic with numeric
}
else
{
//your logic with string
}
}
public Boolean IsNumeric(String value){
try
var numericValue = Int64.Parse(value);
return true;
catch
return false;
}
In this case there is a separate function, which tries to convert it to number, if successful return true, otherwise false. With this you will avoid further code repetition to check if your value is numeric or not.
Once you have your string input, you can use TryParse to see if it is an int or a decimal (among other things)...
string userEntered = Console.ReadLine();
int tempInt;
decimal tempDec;
if(int.TryParse(userEntered, out tempInt))
MessageBox.Show("You entered an int: " + tempInt);
else if(decimal.TryParse(userEntered, out tempDec))
MessageBox.Show("You entered a decimal: " + tempDec);
else MessageBox.Show("You entered a string: " + userEntered);
There is no strict rule for that, User just enters a string value. It could be null or empty string or any other string, which might or might not be convertible to int or decimal or DateTime or any other datatype. So you just have to parse the input data and check whether its convertible to a datatype or not.
You can read user input through
console.readline
to check if it is a string or integer ,you can do something like this
by default user input is string
check the following code snippet
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string input = Console.ReadLine();
Console.WriteLine(input);
int num2;
if (int.TryParse(input, out num2))
{
Console.WriteLine(num2);
}
}
}
Here is an example to check if user enters integer or string value:
Console.WriteLine("Enter value:");
string stringValue = Console.ReadLine();
int intValue;
if(int.TryParse(stringValue, out intValue))
{
// this is int! use intValue variable
}
else
{
// this is string! use stringValue variable
}
Console.WriteLine("enter someting");
string read = Console.ReadLine();
Console.Readline() read user input and will return a string
From here try to convert/parse it to other data type.

check ALL arguments in c# that they can be numeric [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
I am writing a small console application in C# and it requires two numeric parameters/arguments to be passed to it. I am checking for no params, more than 2 params, if two params. I am also converting those params if 2 returned to numeric for calculations I'm doing. One thing I'm not doing is verifying what's being passed is a number so assume program will crap out if I pass a letter. Is there a look routing I can just run to verify the params passed are in deed able to be numbers? I can handle the kick out from there but curious how you check if an argument CAN be a number or not.
Thanks.
JR
I would simplify this task as follows:
Create custom Convert method:
static double Convert(string s)
{
double result;
if (!double.TryParse(s, out result))
result = double.NaN;
return result;
}
Use it in Main:
static void Main(string[] args)
{
var doubles = args.Select(a => Convert(a)).ToArray();
var valid = doubles.All(a => !double.IsNaN(a));
}
Here's one way;
static void Main(string[] args)
{
foreach (var arg in args)
{
int asInt;
// Returns "true" if arg can be parsed as an int and false otherwise;
// If you want to allow doubles you can also try double.TryParse in a similar manner
if (int.TryParse(arg, out asInt))
{
// Handle
}
// Failed to parse argument as an int
else
{
throw new ArgumentException("arg not an int");
}
}
}
You could also use a Regex:
static void Main(string[] args)
{
// Make sure this can is either an int or a double
var regex = new Regex(#"^-?(([0-9]+)|([0-9]+\.[0-9]+(e[0-9]+)?))$");
foreach (var arg in args)
{
if (!regex.IsMatch(arg))
throw new ArgumentException("arg " + arg + " is not an int or double");
}
}
Note a few important features of this regex:
- The "#" literal symbol in front of the regex string
- The ^ and $ to mark the beginning and end of lines - i.e. the string must contain only a number or only a double
- This bans empty strings as well
Edit: I edited the Regex to optionally allow for something like "1.0e100" or "-123", which, as pointed out in the comments, are also perfectly valid ints and doubles. Also, as pointed out in the comments, it's probably better to use int.TryParse or double.TryParse rather than reinventing the wheel.
There's also Char.IsDigit which always feels cleaner to me than checking for a failed parsing attempt. If you care about micro-optimizing, char.IsDigit is probably faster than parsing an invalid string too.
Or, if negative numbers or non-whole numbers are your thing, you can use char.IsNumber
See: https://msdn.microsoft.com/en-us/library/7f0ddtxh(v=vs.110).aspx
public static void Main(string[] args)
{
for(int i = 0; i < args.Length; i++)
{
if(args[i].All((c) => char.IsDigit(c))
{
//It's a number.
}
}
}

Hexadecimal to BigInteger conversion

What is idiomatic way to convert standard hexadecimal string (like "0x0123") to BigInteger in C#?
What I tried requires removing the hex prefix manually:
using System;
using System.Numerics;
using System.Globalization;
namespace TestHex
{
class Program
{
static void Main(string[] args)
{
BigInteger A;
// it does not work
// A = BigInteger.Parse("0x0123");
// it works, but without hex prefix
A = BigInteger.Parse("123", NumberStyles.AllowHexSpecifier);
Console.WriteLine(A);
Console.ReadLine();
}
}
}
According to the MSDN documentation, the idiom is to only accept hexadecimal strings without 0x as input, but then to lie to the user by outputting them prefixed with 0x:
public class Example
{
public static void Main()
{
string[] hexStrings = { "80", "E293", "F9A2FF", "FFFFFFFF",
"080", "0E293", "0F9A2FF", "0FFFFFFFF",
"0080", "00E293", "00F9A2FF", "00FFFFFFFF" };
foreach (string hexString in hexStrings)
{
BigInteger number = BigInteger.Parse(
hexString,
NumberStyles.AllowHexSpecifier);
Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
}
}
}
// The example displays the following output:
// Converted 0x80 to -128.
// Converted 0xE293 to -7533.
// Converted 0xF9A2FF to -417025.
// Converted 0xFFFFFFFF to -1.
// Converted 0x080 to 128.
// Converted 0x0E293 to 58003.
// Converted 0x0F9A2FF to 16360191.
// Converted 0x0FFFFFFFF to 4294967295.
// Converted 0x0080 to 128.
// Converted 0x00E293 to 58003.
// Converted 0x00F9A2FF to 16360191.
// Converted 0x00FFFFFFFF to 4294967295.
That's a really rubbish idiom. I'd invent your own idiom that fits your use case.

Categories

Resources