This question already has answers here:
How to convert numbers between hexadecimal and decimal
(20 answers)
Closed 8 years ago.
Convert Hex to Decimal
Example:
It would ask a Hex. Shown below.
Enter Hex: 8000 8000 1000 0100
Then,
The Result: 32768 32768 4096 256
Convert each hex to decimal.
HEX = DECIMAL
8000 = 32768
8000 = 32768
1000 = 4096
0100 = 256
use string.split(' ') to get your individual hex-numbers as a string-array. Then you can call
int dec = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
to convert each hex into its decimal representation.
Console.Write("Enter HEX: ");
string hexValues = Console.ReadLine();
string[] hexValuesSplit = hexValues.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("HEX = DECIMAL");
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
Console.WriteLine(string.Format("{0} = {1}", hex, Convert.ToDecimal(value)));
}
Console.ReadKey();
P.S. : The original code does not belong to me. For original codes please refer to MSDN
Related
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"))));
This question already has answers here:
How to convert a UTF-8 string into Unicode?
(4 answers)
Closed 3 years ago.
How to encode UTF8 text to Unicode?
string text_txt = "пÑивеÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);
The problem is output: п�?иве�
I need output: привет
Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "пÑивеÑ" it will show you "привет" on Unicode text
Please give some advice thanks
byte[] utf8Bytes = new byte[text_txt.Length];
for (int i = 0; i < text_txt.Length; ++i)
{
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)text_txt[i];
}
text_txt= Encoding.UTF8.GetString(utf8Bytes, 0, text_txt.Length);
from answer: How to convert a UTF-8 string into Unicode?
Well, you probably mean this:
// Forward: given in UTF-8 represented in WIN-1252
byte[] data = Encoding.UTF8.GetBytes("привет");
string text = Encoding.GetEncoding(1252).GetString(data);
// Reverse: given in WIN-1252 represented in UTF-8
byte[] reversedData = Encoding.GetEncoding(1252).GetBytes("привет");
string reversedText = Encoding.UTF8.GetString(reversedData);
Console.WriteLine($"{string.Join(" ", data)} <=> {text}");
Console.WriteLine(reversedText);
Outcome:
208 191 209 128 208 184 208 178 208 181 209 130 <=> привет
привет
Please, note that you've omitted € and , characters:
Ð¿Ñ Ð¸Ð²ÐµÑ - actual string
привет - should be
You need to be explicit about the type of encoding you're using to convert to bytes, (Syste.Text.Encoding.UTF8.GetBytes). eg:
using System;
using System.Text;
public class Program {
public static void Main() {
string text_txt = "пÑивеÑ";
byte[] bytesUtf8 = Encoding.UTF8.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);
Console.WriteLine(text_txt);
}
}
This way UTF8 is used to both encode and decode the string the same way, and when you ensure the same string comes back from the GetString method.
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
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code
foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
{
byte empfrmat =byte.Parse(dr["emp_id"].ToString());
csv += empfrmat;
csv += "\r\n";
}
By using padLeft
eg. "1".PadLeft(8, '0');
Ref. Add zero-padding to a string
strValue.ToString("D8");
D8 means format as a decimal with up to 8 leading zeroes
So you want to change the value to 8 digit format, according to the example that you specified, you can try the following code for this:
int value = 1;
String outputStr = value.ToString("00000000");
Console.WriteLine(outputStr) // this will print 00000001
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");