ulong to hex conversion clarification - c#

I have a reference program which I got online. In that variable data64 is defined as ulong type. Which they're converting to unicode and displaying in a textbox like this:
TextBox1.AppendText = Rxmsg.data64.ToString("X");
The actual value of data64 is "12288092688749907974".
While it displays in textbox the value is "AA88133200035006". I thought it's a simple decimal to hex conversion. So I converted the data64 value to hex but I was wrong. Can anyone please clarify me how the above conversion was made? It's related to one of my projects. It would be very useful for me to proceed further.

reason is the Endianness of the display
IsLittleEndian Yes: 06-50-03-00-32-13-88-AA
IsLittleEndian No: AA-88-13-32-00-03-50-06
fiddle demo and wikipedia link
using System;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
var value = 12288092688749907974u;
var bytes = BitConverter.GetBytes(value);
Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian Yes" : "IsLittleEndian No");
Console.WriteLine(" Value " + BitConverter.ToString(bytes));
Array.Reverse(bytes);
Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian No" : "IsLittleEndian Yes");
Console.WriteLine(" Value " + BitConverter.ToString(bytes));
Console.Read();
}
}
}

Related

C# My code is not doing math.. it is just sticking the numbers together

I am creating a friendly ai whose name is Phil ;), but I need it to be able to do math. I did try, and I also tried +=, but it wont work. For example, if I did 1+1, instead of 2, it would give me 11. Here is my code:
namespace Game
{
public static class Program
{
//commands
public static string enteredCommand;
public static string commanddomath = "doMath";
//Math command stuff
public static string MathOperation;
public static string FirstOperatorNumber;
public static string SecondOperatorNumber;
public static string FinalAwnser;
static void Main()
{
if (enteredCommand == "doMath")
{
Console.WriteLine("Ok");
Console.WriteLine("What Operation should I do?");
MathOperation = Console.ReadLine();
if (MathOperation == "+")
{
Console.WriteLine("Addition! Easy! What is the first number? ex. 6");
FirstOperatorNumber = Console.ReadLine();
Console.WriteLine("Ok, what do you want the second number to be? ex. 8");
SecondOperatorNumber = Console.ReadLine();
FinalAwnser = FirstOperatorNumber + SecondOperatorNumber;
Console.WriteLine("Ok! The awnser is..." + FinalAwnser);
}
}
else
{
Console.WriteLine("That is not a command");
}
Console.ReadKey();
}
}
}
Any help is appreciated!
Thanks
You are storing the user's input (FirstOperatorNumber and SecondOperatorNumber) as strings. The addition operator (+), when applied to two strings, performs an operation called concatenation: it adds the characters from each string to form another string.
But you want addition, which is the result of the addition operator being used on two integers. So you must store the user's input as an integer by replacing 'string' with 'int' in the variable declaration:
public static int FirstOperatorNumber;
public static int SecondOperatorNumber;
The input will still be a string, so you need to convert it as well, like this:
FirstOperatorNumber = Int32.Parse(Console.ReadLine());

Converting Celcius to Fahrenheit - Double.TryParse

I have a successful clean code that does a conversion of Celcius to Fahrenheit using Double.Parse. However, I was curious on how it would look if I did a Double.TryParse but I can't seem to figure out how to complete the code. Once executed, I am able to present "Invalid Code", in my "if, else" but I still get this after my Invaild Output...
Please enter a value for conversion:
30x
Invalid code
The conversion from Celcius to Fahrenheit is: 32
using System;
using System.Text;
namespace CSharpBasics
{
class Program
{
public static double CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
}
else
{
Console.WriteLine("Invalid code");
}
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = CelciusToFarenheit(Console.ReadLine());
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + input);
}
}
}
You should verify your input before the conversion to make sure you never display invalid result for an invalid input but return a message notifying the wrong input first. Something like this:
public static double CelciusToFarenheit(double celcius)
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = Console.ReadLine();
double celcius;
if (Double.TryParse(input, out celcius))
{
var result = CelciusToFarenheit(celcius);
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + result);
}
else
{
Console.WriteLine("Invalid code");
}
}
The method signature public static double CelciusToFarenheit(...) says that this method returns a value - and currently it does.
However, your program flow has to consider invalid input - and thus you need 2 information:
was the entered value a valid value
what's is the value
There are different methods to solve this issue, at least the following:
return a struct or object that holds both information
use the return value and indicate invalid results with exceptions
split the single method into 2 methods, one for checking validity and one for delivering the value.
Let's discuss the 3 options:
3) This might be looking nice, but when you look at Double.TryParse(), you'll likely introduce duplicate code. And when you look at the Main method, the abstraction level will not be the same.
2) Exceptions shall be used for exceptional cases. Wrong user input seems to be a rather usual thing. Not ideal for this case.
1) Sounds quite ok, except that the method might be responsible for 2 things: checking validity and calculating.
To implement that, you don't even need to write a new struct or class. You can simply use Nullable<double> or double?.
Since you're talking about clean code (potentially referring to R.C. Martin), I would start by looking at the main method. Basically I would say the code follows the IPO principle (input, processing, output). However, one line does 2 things:
var input = CelciusToFarenheit(Console.ReadLine());
Also, the variable name input is not so useful here, because it's not the input of the user, but the output after processing.
Proposal for that part:
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
Also, the conversion method does not only convert, but print partial results as well:
Console.WriteLine("Invalid code");
I'd remove that piece and leave it to the output method to handle that case.
Full code:
using System;
namespace CSharpBasics
{
class Program
{
public static double? CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
else
{
return null;
}
}
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
private static void PrintOutput(double? output)
{
if (output == null)
{
Console.WriteLine("Invalid code");
}
else
{
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + output);
}
}
private static string GetCelsiusInputFromUser()
{
Console.WriteLine("Please enter a celsius value for conversion:");
var userInput = Console.ReadLine();
return userInput;
}
}
}
BTW: if you don't have a technical issue, https://codereview.stackexchange.com/ might be better suited for questions regarding clean code.

how we can determine the type of a variable declared with var key word in c#

I want to get input from user and print the type of the input given by user.
I have tried this.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
var userObj = Console.ReadLine();
// if input is 5 it should print it is of type int.
//if input is 5.4 it should print it is of type double.
Console.WriteLine(userObj.GetType());// printing only string
}
}
also tried this but always going false
using System;
class Solution
{
static void Main(String[] args)
{
var userObj = Console.ReadLine();
if (string.Format(userObj) == string .Format("0"))
{
Console.WriteLine("it is of type interger");
}
}
}
You're misunderstanding how var works in C#. C# is a strongly-typed language and as such it's not the same as other languages that use var like JavaScript. Therefore, the variable declared as var already knows what type it is at compile time.
Console.ReadLine() returns a string, therefore the variable userObj in this sense WILL be a string. You will never get anything but a string type.
You can, however, try several things to see if you can convert it to another type. for example:
var userInput = Console.ReadLine();
int x;
if(int.TryParse(userInput, out x))
{
Console.WriteLine("That's an int!");
}
Try parse some with some different number datatypes from biggest to smallest. I assume you want to store the number in the smallest one possible.
float var1;
double var2;
int var3;
if (float.TryParse(urMom, out var1))
Console.WriteLine("Float");
else if (double.TryParse(urMom, out var2))
Console.WriteLine("Double");
else if (int.TryParse(urMom, out var3))
Console.WriteLine("Int");

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.

working with console writeline c#

I need to output the value of d using the same Console.WriteLine. But i am only getting Result not the value of d in output. In what way i can achieve this?
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
Console.WriteLine("Please Enter the first Digit");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter the Second Digit");
b = Convert.ToInt32(Console.ReadLine());
int d = a + b;
Console.WriteLine("Result",(d));
}
}
}
Use:
Console.WriteLine("Result {0}", d);
You are using this overload.
UPDATE
If you look at the link above, you can read how it works. In short, first you specify the formatting, where {0} references the first value of the param object-array, {1} references the second value of the param object-array, etc. After the format, you give the objects to use.
So in your case, you need a single value, which means two arguments, a format, and a value. Hence "Result {0}" with d, which will become (when for example d=10) "Result 10".
Note: also removed the unnecessary parenthesis.
Use
Console.WriteLine("Result {0}", d);

Categories

Resources