I have a program written in Delphi is converting 11 to 0xB and 28 to 0x1c. I tried to convert 11 (decimal to Hex) in c# using this:-
var deciValue01 = 11;
var deciValue02 = 28;
var deciValue03 = 13;
System.Diagnostics.Debug.WriteLine(string.Format("11 = {0:x}", deciValue01));
System.Diagnostics.Debug.WriteLine(string.Format("28 = {0:x}", deciValue02));
System.Diagnostics.Debug.WriteLine(string.Format("13 = {0:x}", deciValue03));
but the results I am getting is:-
11 = b
28 = 1c
13 = d
Wondering how to convert 11 to '0xB' and 28 to '0x1c' and 13 to '0xD'? Isn't it I need to change from Decimal to Hex?
You just need to use X to make it capital hex digits instead of lower case, and add the 0x yourself:
// Add using System.Diagnostics; at the top of the file... no need to
// explicitly qualify all your type names
Debug.WriteLine(string.Format("11 = 0x{0:X}", deciValue01));
Debug.WriteLine(string.Format("28 = 0x{0:X}", deciValue02));
Debug.WriteLine(string.Format("13 = 0x{0:X}", deciValue03));
Note that the deciValue01 values are neither "decimal" nor "hex" themselves. They're just numbers. The concept of "decimal" or "hex" only makes sense when you're talking about a textual representation, at least for integers. (It matters for floating point, where the set of representable types depends on the base used.)
Try This
int value = Convert.ToInt32(/*"HexValue"*/);
String hexRepresentation = Convert.ToString(value, 16);
It sounds like you want this...
var deciValue01 = 11;
var deciValue02 = 28;
var deciValue03 = 13;
System.Diagnostics.Debug.WriteLine(string.Format("11 = 0x{0:x}", deciValue01));
System.Diagnostics.Debug.WriteLine(string.Format("28 = 0x{0:x}", deciValue02));
System.Diagnostics.Debug.WriteLine(string.Format("13 = 0x{0:x}", deciValue03));
Related
Let's say I have text file like this
<pre>----------------
hPa m C
---------------------
1004.0 28 13.6
1000.0 62 16.2
998.0 79 17.2
992.0 131 18.0
<pre>----------------
Sometext here
1000.0 10 10.6
1000.0 10 11.2
900.0 10 12.2
900.0 100 13.0
<aaa>----------------
How Can I Create Array in C# that reads text file from line number 5 (1004.0) to just before line that starts with string <pre>-
I used string[] lines = System.IO.File.ReadAllLines(Filepath);
To make each line in the array
The problem is I want only numbers of first section in the array in order to separate them later to another 3 arrays (hPa, m, C) .
Here's a possible solution. It's probably way more complicated than it should be, but that should give you an idea of possible mechanisms to further refine your data.
string[] lines = System.IO.File.ReadAllLines("test.txt");
List<double> results = new List<double>();
foreach (var line in lines.Skip(4))
{
if (line.StartsWith("<pre>"))
break;
Regex numberReg = new Regex(#"\d+(\.\d){0,1}"); //will find any number ending in ".X" - it's primitive, and won't work for something like 0.01, but no such data showed up in your example
var result = numberReg.Matches(line).Cast<Match>().FirstOrDefault(); //use only the first number from each line. You could use Cast<Match>().Skip(1).FirstOrDefault to get the second, and so on...
if (result != null)
results.Add(Convert.ToDouble(result.Value, System.Globalization.CultureInfo.InvariantCulture)); //Note the use of InvariantCulture, otherwise you may need to worry about , or . in your numbers
}
Do you mean this?
System.IO.StreamReader file = new System.IO.StreamReader(FILE_PATH);
int skipLines = 5;
for (int i = 0; i < skipLines; i++)
{
file.ReadLine();
}
// Do what you want here.
This question already has answers here:
Convert integer to hexadecimal and back again
(11 answers)
Closed 9 years ago.
i have a text box on my form. I want to write "0x31" as a string to my textbox and then when i clicked a button, i want to convert this string to 0x31 as a hexadecimal value.
How can i convert this string to hexadecimal value?
int i = Convert.ToInt32("0x31", 16);
Console.WriteLine("0x" + i.ToString("X2"))
string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
// Get the character corresponding to the integral value.
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
hex, value, stringValue, charValue);
}
Example From: http://msdn.microsoft.com/en-us/library/bb311038.aspx
Hexadecimal is just a representation of an value, it is not a value itself.
This page will tell you everything you need to know about parsing and displaying hex in C#
http://msdn.microsoft.com/en-us/library/bb311038.aspx
First to clear up: The string is in hexadecimal format, when you convert it to a value it's just a numeric value, it's not hexadecimal.
Use the Int32.Parse method with the NumberStyle.HexNumber specifier:
string input = "0x31";
int n;
if (input.StartsWith("0x")) {
n = Int32.Parse(input.Substring(2), NumberStyles.HexNumber);
} else {
n = Int32.Parse(input);
}
The string hex value is a representation of a value. The actual string value can be converted to whatever you like(float, int etc.)
There are several ways to do the conversion. Simple example:
// convert to int from base 16
int value = Convert.ToInt32(hex, 16);
Note that hex is just a representation of a value - so what you are really asking is how you can parse a value from the string - do it like so:
int val = int.Parse("0x31", NumberStyles.HexNumber);
val now contains an int with the hex value 0x31.
I Have a string array with 5 values, i want the program to loop even though i don't enter a value for the arrays. If I split the arrays without inserting anything (pressing ..... (5 times "." to split the array) then it doesn't crash it will just loop. But if i just hit enter, then the program crashes.
Is there a way to fix the loop so that even though there is no kind of input, that it won't crash? (It also crashes if you don't complete all 5 values.)
Net = Console.ReadLine();
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
temp = oktet[0]; //inputs value of array in temp
NaN = int.TryParse(temp, out Net0);
temp = oktet[1];
NaN = int.TryParse(temp, out Net1);
temp = oktet[2];
NaN = int.TryParse(temp, out Net2);
temp = oktet[3];
NaN = int.TryParse(temp, out Net3);
temp = oktet[4];
NaN = int.TryParse(temp, out subnet);
}
while (!NaN | Net0 > 255 | Net0 < 0 | Net1 > 255 | Net1 < 0 | Net2 > 255 | Net2 < 0 | Net3 > 255 | Net3 < 0 | subnet > 32 | subnet < 0);
I know it's pretty amateur, but hey, we're here to learn right? :)
Thanks in advanced!
You can try to do something like this:
string[] oktet = Net.Split('.', '/'); // size array according to input
if (oktet.Length != 5) continue; // reloop on bad input
Those two lines of code replace these:
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
I would just use some command line option library if you could (unless this is homework where you need to learn how to validate input, parse, etc.). See NDesk.Options (http://www.ndesk.org/Options), available via Nuget as well. See the following for required options: How to enforce required command-line options with NDesk.Options?
var userInput = Console.ReadLine();
var userInputSplit = userInput.Split('.', '/');
var numbers = userInputSplit.Select(word =>
{
int result;
if (byte.TryParse(word, out result))
return (byte?)result;
return (byte?)null; });
});
var inputComplete = number.Where(number => number.HasValue).Count() == 4;
The problem is that your variable oktet isn't an array of 5, because you're assigning something else in it.
string[] oktet = new string[5]; // Assigns an array of 5
oktet = Net.Split('.', '/'); //assigns the result of the split to the variable
So, oktet is has the result of the split, and its length.
BTW, Classes start with a capital letter, and the variables should start with a small letter.
Coding standards will make the code more readable, and will help you tell the difference between items.
I have a double and I want to format it with the following rules:
If there are no decimal places show just the number (see 100 example below)
If there are any decimal places show 2 decimal places
So, as a few examples:
100 --> 100
99.958443534 --> 99.96
99.1 -> 99.10
You could check if its a whole number, the use the type of formatting based on that:
string res = string.Format(((number % 1) == 0) ? "{0:0}" : "{0:0.00}", number);
What about:
var a = 100;
var b = 99.95844354;
var aAnswer = a.ToString("0.##"); //aAnswer is "100"
var bAnswer = b.ToString("0.##"); //bAnswer is "99.96"
You can use:
decimal a = 99.949999999M;
Math.Round(a, 2); // Returns 99.95
**Hey i was working on an application which converts any basenumber like (2,8,10,16,etc) to user's desire base system. I am having a problem in converting a binary number to its octal number can anyone help me out?
I tried everthing like
// i am taking a binary number in value and then converting it to base 8
Int32 value = int.Parse(convertnumber);
Console.WriteLine(Convert.ToString(value, 8));
For example:
value =10011
Answer should be this "23" but using the above code i am getting "23433"
"23433" is is the correct answer, when converting "10011" in base 10 to base 8.
You may have meant to interpret "10011" as a binary number. In which case, you want:
int value = Convert.ToInt32(convertnumber, 2);
Edit: in response to comments, here's almost-complete code:
string val = "10011";
int convertnumber = Convert.ToInt32(val, 2);
Console.WriteLine(Convert.ToString(convertnumber, 8)); // prints "23"
string binary = "10011";
int integer = Convert.ToInt32(binary, 2);
Console.WriteLine(Convert.ToString(integer, 8));
Output: 23
In this example we convert the binary string representation to an integer and from an integer to the octal string representation.
int value = Convert.ToInt32(convertnumber, 2);
Console.WriteLine(Convert.ToString(value, 8));
You are taking a base 10 number 10011 and converting it to base 8. Which is 23433.
If you want to do this manually (so you understand what is going on) here is a suggestion:
First pad the binary string to be divisable by 3 ( 3 bits = 1 octal digit )
string binary = "10011";
int pad = binary.Length % 3;
binary = new string('0', 3-pad) + binary;
Then process each three bits into one octal digit
int n = binary.Length / 3;
char[] bin_digits = binary.ToCharArray();
char[] oct_digits = new char[n];
for (int i = 0; i < n; i++)
{
int digit = bin_digits.Skip(3 * i).Take(3).Aggregate(0,
(x, v) => (int)v - (int)'0' + 2 * x);
// x is the value accumulation
// v is a char '0' or '1' representing a bit and is converted to int 0, 1
oct_digits[i] = (char)(digit + (int)'0');
// convert int to char digit
}
Convert the digits array into a string
string oct_value = new string(oct_digits);
Example results:
"10011" -> "23"
"11000" -> "30"
"1011011" -> "133"
Naturally, int.Parse parses a decimal number. If your input is binary, then you'll need to first do a conversion from binary to integer.
Int32 value = Convert.ToInt32( "10011", 2 );
Console.WriteLine(Convert.ToString(value, 8));
That's because int.Parse is converting 10011 to, well, 10011 in decimal. It is not converting it from 10011 binary to 23 octal (19 decimal) as you want it to.