The C # language has a lot to learn, and here we introduce C # implementation conversion hexadecimal, including aspects such as the enumeration value used to denote hexadecimal as hexnumber.
C # Implementation Conversion hex
Any data is stored in binary form within the computer, so the system is not related to the storage of the data, but to the input and output. So, for a binary conversion, we only care about the results in the string.
In the 4th above, the ToString () method can be used to convert a numeric value to a string, but in a string, the result is displayed in decimal. Now, with some parameters, we can convert the C # implementation to hexadecimal-using the ToString (string) method.
This requires a string parameter, which is the format specifier. The hexadecimal format specifier is "x" or "X", and the difference between the two format specifiers is mainly the a-f six digits: "X" represents a-f using lowercase letters, whereas "X" means that A-f uses large letters. The following example:
private void TestHex() {
int a = 188;
this.textBox1.Text = "";
this.textBox1.AppendText("a(10) = " + a.ToString() + "\n");
this.textBox1.AppendText("a(16) = " + a.ToString("x") + "\n");
this.textBox1.AppendText("a(16) = " + a.ToString("X") + "\n");
}
The results of the operation are as follows:
a(10) = 188
a(16) = bc
a(16) = BC
At this point, we may have another requirement, that is, in order to display the results neatly, we need to control the length of the hexadecimal representation, if the length is not enough, with a leading 0 fill. To solve this problem, we just need to write a number representing the length of the format specifier "x" or "X". For example, to limit the length of 4 characters, you can write "X4". In the example above, add a sentence:
this.textBox1.AppendText("a(16) = " + a.ToString("X4") + "\n");
The result will be output a (= 00BC).
Now, let's talk about how to convert a string that represents a hexadecimal number to an integral type. This transformation also requires the help of the Parse () method. Here, I need the Parse (string, System.Globalization.NumberStyles) method. The first parameter is a string that represents a hexadecimal number, such as "AB", "20" (representing 32 decimal), and so on. The second parameter, System.Globalization.NumberStyles, is an enumeration type, which is used to indicate that the hexadecimal enumeration value is hexnumber. So if we want to convert "AB" to an integral type, we should write this: int b = Int. Parse ("AB", System.Globalization.NumberStyles.HexNumber), the resulting B value is 171.