The meaning of this code about converting in C#? - c#

i had a function containing code like this:
Random x = new Random();
int key = x.Next(0x21, 0x7B);
string nxt = Convert.ToString(key.ToString("X")) +
Convert.ToString(key.ToString("X"))
+ Convert.ToString(key.ToString("X"))
+ Convert.ToString(key.ToString("X"));
Im very new to C#, help me, thank a lot

That code is choosing a random number between 0x21 and 0x7B, converting it to a string in hex and repeating it four times in nxt.
There are better ways to create a string with a single character multiple times (for example, the string constructor that accepts a character and a count), and the Convert.ToString call is useless since int.ToString already returns a string.

The first two lines pick a random integer between 33 and 122 inclusive (the 0xs in .Next() mean those numbers are expressed in hexadecimal notation).
The key.ToString("X") part takes that random integer, converts it to hexadecimal notation, and returns it as a string.
As Blindy pointed out, the Convert.ToString() is redundant and not necessary since it is converting a string to a string.
The final "nxt" variable would consist of that new hexadecimal number (as a string) repeated four times.
Here's a couple of other ways to get that string repeated four times:
string nxt = new StringBuilder().Insert(0, key.ToString("X"), 4).ToString();
string nxt = String.Concat(Enumerable.Repeat(key, 4));
string nxt = $"{key}{key}{key}{key}";

Related

How to replace multiple characters in a string with other multiple characters (another string) without replacing other ocurrences?

I'm making a console application for IP assignment where a user simply enters the number of networks, the number of hosts per network and the initial network IP address, and this generates the full IP assignment table.
My biggest issue right now is that say I have a string with "172.16.0.0".
I want to grab the 0 at the end, convert it to an int, add a certain number of hosts (say, 0 + 512), and if it goes over 255, I want it to instead grab the previous 0 and replace it with a 1 instead then test it again. But I'm mostly having issues with replacing the numbers in the initial string. Since strings aren't mutable, I obviously have to make a new string with the change, but I can't see how to do this.
I've so far tried finding the index where the change will be made using the string.split function and indexof and making that an int variable called datIndex. Then I change the "172.16.0.0" string to a character array, then tried swapping the character in the previously defined index, however this limits me to a single character, which wouldn't work for a number with more than one digit. Also tried using stringbuilder but the stringbuilder object seems to be a char type so I end up in the same place, can't equal the value in the index I want to change to the new number.
string test = "172.16.0.0";
int datIndex = test.IndexOf(test.Split('.')[2]);
char[] c = test.ToCharArray();
c[datIndex] = '201'; //Not possible because more than one digit
//Also tried the following
datIndex = test.IndexOf(test.Split('.')[2]);
StringBuilder sb = new StringBuilder(test);
sb[datIndex] = '201'; //Cannot implicitly convert type string to char
string temp2 = sb.ToString();
test = temp2; //Changed string
In this example, I'd like to change the penultimate "0" in the "172.16.0.0" string to a "201" (this number would be obtained by a sum of two numbers so ideally they'd both first be integers).
However with both methods I've tried, I can't fit a number bigger than one digit into that index.
This is maybe what you are looking for:
string ip = "127.16.0.0";
string ipNumbers = ip.Split('.');
int a = int.Parse (ipNumbers[0]);
int b = int.Parse (ipNumbers[1]);
int c = int.Parse (ipNumbers[2]);
int d = int.Parse (ipNumbers[3]);
//now you have in a,b,c and d all the ip numbers, do the math with them and then do this:
ip = $"{a}.{b}.{c}.{d}";

Is there a different way to convert to hexadecimal?

I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "
The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.
string TextToConvert = "Test Andrei";
TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);
List<char> Chars = TextToConvert.ToCharArray().ToList();
string CharValue = "";
string secondHexConvert = "";
foreach(char c in Chars)
{
CharValue+=Convert.ToInt32(c);
secondHexConvert+=Convert.ToString(c, 16)+" ";
}
string hexValue = String.Format("{0:X}", CharValue)+" ";
I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"
To convert such a big integer to a hexadecimal string, use the aptly named BigInteger type:
var num = BigInteger.Parse("841011151163265110100114101105");
string hex = num.ToString("X");
Console.WriteLine(hex);
will output:
0A9D741E82C98FC6A137B75371
but here's a snag, the output you showed in your question is somewhat different, let me show it together with what the code above produces:
0A9D741E82C98FC6A137B75371
a9d741e82c990000000000000
As you can see, the numbers start the same but your example then ends up with lots of zeroes.
The only way I understand this could happen is that they're in fact not using a type that can hold that many significant digits, so you get a rounding error.
Many of the dynamic programming languages allows you to use floating point numbers and integers interchangeably, I guess this is what happened, a floating point type that can only hold 17-18 significant digits or some such was used, and you lost precision. .NET, however, doesn't have built-in support for converting floating point types to hexadecimal.
You can see that .NET produces the exact value by converting back:
Console.WriteLine(BigInteger.Parse(hex, System.Globalization.NumberStyles.HexNumber));
outputs:
841011151163265110100114101105
In other words, I'm not sure you can get the exact same results in .NET.
Corollary: Don't use that site for this kind of conversion!
You can use the following code to convert a string to hexadecimal:
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
And you just call it using:
string testString = "11111111";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);

What does Int32.Parse do exactly?

I am just beginning to learn C#. I am reading a book and one of the examples is this:
using System;
public class Example
{
public static void Main()
{
string myInput;
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
Console.WriteLine(myInt);
Console.ReadLine();
}
}
When i run that and enter say 'five' and hit return, i get 'input string not in correct format' error. The thing i don't understand is, i converted the string myInput to a number didn't i? Microsoft says that In32.Parse 'Converts the string representation of a number to its 32-bit signed integer equivalent.' So how come it doesn't work when i type the word five? It should be converted to an integer shouldn't it... confused. Thanks for advice.
'five' is not a number. It's a 4-character string with no digits in it. What parse32 is looking for is a STRING that contains numeric digit characters. You have to feed it "5" instead.
The string representation that Int32.Parse expects is a sequence of decimal digits (base 10), such as "2011". It doesn't accept natural language.
What is does is essentially this:
return 1000 * ('2' - '0')
+ 100 * ('0' - '0')
+ 10 * ('1' - '0')
+ 1 * ('1' - '0');
You can customize Int32.Parse slightly by passing different NumberStyles. For example, NumberStyles.AllowLeadingWhite allows leading white-space in the input string: " 2011".
The words representing a number aren't converted; it converts the characters that represent numbers into actual numbers.
"5" in a string is stored in memory as the ASCII (or unicode) character representation of a 5. The ASCII for a 5 is 0x35 (hex) or 53 (decimal). An integer with the value '5' is stored in memory as an actual 5, i.e. 0101 binary.

Thousand separated value to integer

I want to convert a thousand separated value to integer but am getting one exception.
double d = Convert.ToDouble("100,100,100");
is working fine and getting d=100100100
int n = Convert.ToInt32("100,100,100");
is getting one format exception
Input string was not in a correct format
Why?
try this:
int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);
Note that the Parse method will throw an exception on an invalid string, so you might also want to check out the TryParse method as well:
string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
// if you are here, you were able to parse the string
}
What Convert.ToInt32 is actually calling in your example is Int32.Parse.
The Int32.parse(string) method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).
Since your's contained commas, it threw an exception.
Because you're supposed to specify a string containing a plain integer number (maybe preceded by +/- sign), with no thousands separator. You have to replace the separator befor passing the string to the ToInt32 routine.
You can't have separators, just numbers 0 thru 9, and an optional sign.
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx

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