c# how to get hex literal from integer - c#

the are many ways to convert an integer to hex STRING, but is there a way to cast it to a hex literal as in?
string = z
integer = 122
hex = 0X7A

an integer remains an integer irrespective of the representation. You can assign the hex value directly to an int. The representation makes only a difference when you want to display it or use it as a string:
int integer = 122;
int integer_in_hex = 0X7A;
For the display you can use the format string "X2" which means to display the munber in hex with the length of 2 positions:
Console.WriteLine(integer_in_hex.ToString("X2"));
Console.WriteLine(integer.ToString("X2"));
the output is the same:
7A 7A
for more information please read the documentation

Are you looking for string's dump (representing characters within the string with their hex values)? Something like this:
using System.Linq;
...
string test = "hello z";
// To dump
string dump = string.Join(" ", test.Select(c => $"0x{(int)c:X2}"));
// From dump
string restore = string.Concat(dump
.Split(' ')
.Select(item => (char)Convert.ToInt32(item, 16)));
Console.WriteLine(dump);
Console.WriteLine(restore);
Outcome
0x68 0x65 0x6C 0x6C 0x6F 0x20 0x7A
hello z

Related

How to convert a number (larger than 0xFFFF) that represents a Unicode character to its equivalent string in C#

For example, a character '𠀀' in CJK Unified Ideographs Extension A; its unicode value is 0x20000, as a char in C# can't represent such character, so I wonder if I could convert it to string, my question is:
If I give you a number like 0x20000, how to convert it and let me get its equivalent string like "𠀀"
You can use char.ConvertFromUtf32 for that:
int utf32 = 0x20000;
string text = char.ConvertFromUtf32(utf32);
string itself is a sequence of UTF-16 code units, in this case U+D840 and U+DC00, which you can see by printing out the individual char values:
int utf32 = 0x20000;
string text = char.ConvertFromUtf32(utf32);
Console.WriteLine(((int) text[0]).ToString("x4")); // d840
Console.WriteLine(((int) text[1]).ToString("x4")); // dc00

how to convert a hex value from a byte array as an interpreted ASCII number into an integer?

I'm just starting with the c# programming and
as the heading describes, I'm looking for a way to convert a number passed to me as an ASCII character in a byte[] to an integer. I often find the way to convert a hex-byte to ASCII-char or string. I also find the other direction, get the hex-byte from a char. Maybe I should still say that I have the values displayed in a texbox for control.
as an example:
hex- code: 30 36 38 31
Ascii string: (0) 6 8 1
Integer (dez) should be: 681
so far I have tried all sorts of things. I also couldn't find it on the Microsoft Visual Studio website. Actually this should be relatively simple. I am sorry for my missing basics in c#.
Putting together this hex-to-string answer and this integer parsing answer, we get the following:
// hex -> byte array -> string
var hexBytes = "30 36 38 31";
var bytes = hexBytes.Split(' ')
.Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
.ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);
// parse string as integer
int x = 0;
if (Int32.TryParse(asciiStr, out x))
{
Console.WriteLine(x); // write to console
}
else
{
Console.WriteLine("{0} is not a valid integer.", asciiStr); // invalid number, write error to console
}
Try it online
A typical solution of the problem is a Linq query. We should
Split initial string into items
Convert each item to int, treating item being hexadecimal. We should subtract '0' since we have not digit itself but its ascii code.
Aggregate items into the final integer
Code:
using System.Linq;
...
string source = "30 36 38 31";
int result = source
.Split(' ')
.Select(item => Convert.ToInt32(item, 16) - '0')
.Aggregate((sum, item) => sum * 10 + item);
If you want to obtain ascii string you can
Split the string
Convert each item into char
Join the chars back to string:
Code:
string source = "30 36 38 31";
string asciiString = string.Join(" ", source
.Split(' ')
.Select(item => (char)Convert.ToInt32(item, 16)));
To convert a byte array containing ASCII codes to an integer:
byte[] data = {0x30, 0x36, 0x38, 0x31};
string str = Encoding.ASCII.GetString(data);
int number = int.Parse(str);
Console.WriteLine(number); // Prints 681
To convert an integer to a 4-byte array containing ASCII codes (only works if the number is <= 9999 of course):
int number = 681;
byte[] data = Encoding.ASCII.GetBytes(number.ToString("D4"));
// data[] now contains 30h, 36h, 38h, 31h
Console.WriteLine(string.Join(", ", data.Select(b => b.ToString("x"))));

C# Converting Problems with String Array to Int Array

I`m working with C# and I have a problem at converting a string array to a int array.
First I created a string number with the Console
Console.WriteLine("Geben Sie die Nummer ein:");
string wert = Console.ReadLine();
Then I converted the string to a array
char[] wertarray = wert.ToCharArray();
wertarray1 = new string(wertarray);*
And now comes the problem. I want to convert the string array to a int array, but e.g. for string wertarray1[0]=1, the int array has the value 49.
int wertarray2 = Convert.ToInt16(wertarray1[0]);
Normal the Int value should be 1, but I don`t know where the problem is.
I tried the solutions for "convert a string array to a int array" from this forum, but i still had the problem that the int value get a strange number.
I´m looking forward for help.
Thanks :-).
Convert.ToInt16(Char) takes the numeric value of the char (i.e. its Unicode code-point value) and returns that number. While you might think Convert.ToInt16('1') should return 1, consider what would happen if you tried Convert.ToInt16('#') for example.
Use Int16.Parse (or TryParse) to actually parse a string to numbers. As you're working with individual characters to represent 0-9 you might as well do it using simple arithmetic without the need to call any Parse function:
String line = Console.ReadLine();
List<Int16> numbers = new List<Int16>( line.Length );
foreach(Char c in line) {
Int16 charValue = (Int16)c;
if( charValue < 48 || charValue > 57 ) throw new Exception("char is not a digit");
Int16 value = charValue - 48;
numbers.Add( value );
}
Answers provided already explain your problem and provide solution too.
In general, you can convert the char to string and parse them to integer (not the best performance though).
If you have all numeric string
var numStr = "136";
var numbers = numStr.Select(n => int.Parse(n.ToString())).ToList(); // {1, 3, 6}
If your string contains non numbers too
var mixStr = "1.k78Tj_n";
int temp;
var numbers2 = new List<int>();
mixStr.ToList().ForEach(n =>
{
if (int.TryParse(n.ToString(), out temp))
numbers2.Add(temp);
}); //{ 1, 7, 8 }
You're getting the Unicode code point value of the characters in your input stream -- 49 is the unicode value for the character 1.
If you want to convert a unicode character that is a digit to the numeric value of that digit, you can use System.Globalization.CharUnicodeInfo.GetDecimalDigitValue(char c):
var wertarray2 = wert.Select(c => (short)CharUnicodeInfo.GetDecimalDigitValue(c)).ToArray();
This handles all digits (including superscripted numbers) not just the standard ASCII digits.

Trying to decode hex to binary representation in C#

I'm saving a bitarray (40 bits) from Python (using bitarray lib) to Redis.
When I retrieve this value from Redis, I get: \xe8\x00\x00\x00\x00
How do I convert this value to "01010101" in C#?
Thank you!
EDIT:
When i use this form:
http://easycalculation.com/hex-converter.php, the binary value returned is what i'm expecting.
You could do this:
// Chop up the string into individual hex values
string[] hexStrings = hexString.Split(new[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
// Convert the individual hex strings into integers
int[] values = hexStrings.Select(s => Convert.ToInt32(s, 16)).ToArray();
// Convert the integers into 8-character binary strings
string[] binaryStrings = values.Select(v => Convert.ToString(v, 2).PadLeft(8, '0')).ToArray();
// Join the strings together
string binaryString = string.Join("", binaryStrings);
EDIT - Here's an example of what you could do if you want to use a BitArray:
// Chop up the string into individual hex values
string[] hexStrings = hexString.Split(new[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
// Convert the individual hex strings into bytes
byte[] bytes = hexStrings.Select(s => Convert.ToByte(s, 16)).ToArray();
BitArray bitArray = new BitArray(bytes);

Converting string value to hex decimal

i am making application in c#. In that implication i have string which contain decimal value as
string number="12000";
The Hex equivalent of 12000 is 0x2EE0.
Here i want to assign that hex value to integer variable as
int temp=0x2EE0.
Please help me to convert that number.
Thanks in advance.
string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
/* Output:
Hexadecimal value of H is 48
Hexadecimal value of e is 65
Hexadecimal value of l is 6C
Hexadecimal value of l is 6C
Hexadecimal value of o is 6F
Hexadecimal value of is 20
Hexadecimal value of W is 57
Hexadecimal value of o is 6F
Hexadecimal value of r is 72
Hexadecimal value of l is 6C
Hexadecimal value of d is 64
Hexadecimal value of ! is 21
*/
SOURCE: http://msdn.microsoft.com/en-us/library/bb311038.aspx
An int contains a number, not a representation of the number. 12000 is equivalent to 0x2ee0:
int a = 12000;
int b = 0x2ee0;
a == b
You can convert from the string "12000" to an int using int.Parse(). You can format an int as hex with int.ToString("X").
Well you can use class String.Format to Convert a Number to Hex
int value = Convert.ToInt32(number);
string hexOutput = String.Format("{0:X}", value);
If you want to Convert a String Keyword to Hex you can do it
string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
If you want to convert it to hex string you can do it by
string hex = (int.Parse(number)).ToString("X");
If you want to put only the number as hex. Its not possible. Becasue computer always keeps number in binary format so When you execute int i = 1000 it stores 1000 as binary in i. If you put hex it'll be binary too. So there is no point.
you can try something like this if its going to be int
string number = "12000";
int val = int.Parse(number);
string hex = val.ToString("X");

Categories