Use a Decimal Value as a Hexadecimal Value - c#

I have the int 15 (or the string "15", that's just as easy), and I need to use it to create the value:
"\u0015"
Is there some conversion which would accomplish this? I can't do this:
"\u00" + myInt.ToString()
Because the first literal is invalid. Is there a simple way to get this result?
(If you're curious, this is for integrating with a hardware device where the vendor sometimes expresses integer values as hexadecimal. For example, I'd need to send today's date to the device as "\u0015\u0010\u0002".)

Given that you want a Unicode code point of 21, not 15, you should definitely start with the string "15". If you try to start with 15 as an int, you'll find you can't express anything with a hex representation involving A-F...
So, given "15" the simplest way of parsing that as hex is probably:
string text = "15";
int codePoint = Convert.ToInt32(text, 16);
After that, you just need to cast to char:
string text = "15";
int codePoint = Convert.ToInt32(text, 16);
char character = (char) codePoint;
Note that this will only work for code points in the Basic Multilingual Plane (BMP) - i.e. U+0000 to U+FFFF. If you need to handle values beyond that (e.g. U+1F601) then you should use char.ConvertFromUtf32 instead:
string text = "15";
int codePoint = Convert.ToInt32(text, 16);
string character = char.ConvertFromUtf32(codePoint);

Unicode literals in strings are resolved at compile-time, that's why "\u00" + myInt.ToString() doesn't work (the ToString() and concatenation are evaluated at runtime).
You could cast the int to char:
int unicodeCodePoint = 15; // or 21
char c = (char)unicodeCodePoint;

Related

Convert from String to BigInteger in C# without cutting off leading zero's.

Working on a project where I need to do a bitwise & between two similar 168 character bitarrays. I am working in C# and when I attempt to convert from String to BigInteger, the leading zero's are being truncated. Is there anything I can do to save these characters?
Basically:
string bits = "000000000000000000000000000000000000000000000000000000000000000000001111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
BigInteger bigIntBits = BigInteger.Parse(bits);
// I am being returned 1111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
Anything will help. Thank you in advance.
You can simply do this:
string bits = "000000000000000000000000000000000000000000000000000000000000000000001111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
// convert to big integer
var bigIntBits = BigInteger.Parse(bits);
int index = bits.IndexOf('1');
string backToString = new string('0', index) + bigIntBits.ToString();

Converting a string getting Wrong value

I write a simple code and need to get each number in a string as an Integer
But when I try to use Convert.ToInt32() it give me another value
Example:
string x="4567";
Console.WriteLine(x[0]);
the result will be 4 , but if i try to use Convert
Console.WriteLine(Convert.ToInt32(x[0]));
it Give me 52 !!
I try using int.TryParse() and its the same
According to the docs:
The ToInt32(Char) method returns a 32-bit signed integer that represents the UTF-16 encoded code unit of the value argument. If value is not a low surrogate or a high surrogate, this return value also represents the Unicode code point of value.
In order to get 4, you'd have to convert it to a string before converting to int32:
Console.WriteLine(Convert.ToInt32(x[0].ToString()));
you can alternatively do this way to loop through all characters in a string
foreach (char c in x)
{
Console.WriteLine(c);
}
Will Print 4,5,6,7
And as suggested in earlier answer before converting to integer make that as a sting so it doesn't return the ascii code
A char is internally a short integer of it's ASCII representation.
If you cast/convert (explicitly or implicitly) a char to int, you will get it's Ascii value. Example Convert.ToInt32('4') = 52
But when you print it to Console, you are using it's ToString() method implicitly, so you are actually printing the ASCII character '4'. Example: Console.WriteLine(x[0]) is equivalent to Console.WriteLine("4")
Try using an ASCII letter so you will notice the difference clearly:
Console.WriteLine((char)('a')); // a
Console.WriteLine((int)('a')); // 97
Now play with char math:
Console.WriteLine((char)('a'+5)); // f
Console.WriteLine((int)('a'+5)); // 102
Bottom line, just use int digit = int.Parse(x[0]);
Or the funny (but less secure) way: int digit = x[0] - '0';
x isnt x[0], x[0] is the first char, '4' which is 52.

C# Convert Int64 to String using a cast

How do you convert an integer to a string? It works the other way around but not this way.
string message
Int64 message2;
message2 = (Int64)message[0];
If the message is "hello", the output is 104 as a number;
If I do
string message3 = (string)message2;
I get an error saying that you cant convert a long to a string. Why is this. The method .ToString() does not work because it converts just the number to a string so it will still show as "104". Same with Convert.ToString(). How do I make it say "hello" again from 104? In C++ it allows you to cast such methods but not in C#
message[0] gives first letter from string as char, so you're casting char to long, not string to long.
Try casting it back to char again and then concatenate all chars to get entire string.
ToString() is working exactly correctly. Your error is in the conversion to integer.
How exactly do you expect to store a string composed of non-numeric digits in a long? You might be interested in BitConverter, if you want to treat numbers as byte arrays.
If you want to convert a numeric ASCII code to a string, try
((char)value).ToString()
Another alternative approach is using ASCII.GetBytes method as below
string msg1 ="hello";
byte[] ba = System.Text.Encoding.ASCII.GetBytes(msg1);
//ba[0] = 104
//ba[1] = 101
//ba[2] = 108
//ba[3] = 108
//ba[4] = 111
string msg2 =System.Text.Encoding.ASCII.GetString(ba);
//msg2 = "hello"
Try this method:
string message3 = char.ConvertFromUtf32(message2);
104 is the value of "h" not "hello".
There is no integer representation of a string, only of a char. Therefore, as stated by others, 104 is not the value of "hello" (a string) but of 'h' (a char) (see the ASCII chart here).
I can't entirely think of why you'd want to convert a string to an int-array and then back into a string, but the way to do it would be to run through the string and get the int-value of each character and then reconvert the int-values into char-values and concatenate each of them. So something like
string str = "hello"
List<int> N = new List<int>();
//this creates the list of int-values
for(int i=0;i<str.Count;i++)
N.Add((int)str[i]);
//and this joins it all back into a string
string newString = "";
for(int i=0;i<str.Count;i++)
newString += (char)N[i];

How to insert a Symbol (Pound, Euro, Copyright) into a Textbox

I can use the Alt Key with the Number Pad to type symbols, but how do I programmatically insert a Symbol (Pound, Euro, Copyright) into a Textbox?
I have a configuration screen so I need to dynamically create the \uXXXX's.
In C#, the Unicode character literal \uXXXX where the X's are hex characters will let you specify Unicode characters. For example:
\u00A3 is the Pound sign, £.
\u20AC is the Euro sign, €.
\u00A9 is the copyright symbol, ©.
You can use these Unicode character literals just like any other character in a string.
For example, "15 \u00A3 per item" would be the string "15 £ per item".
You can put such a string in a textbox just like you would with any other string.
Note: You can also just copy (Ctrl+C) a symbol off of a website, like Wikipedia (Pound sign), and then paste (Ctrl+V) it directly into a string literal in your C# source code file. C# source code files use Unicode natively. This approach completely relieves you from ever even having to know the four hex digits for the symbol you want.
To parallel the example above, you could make the same string literal as simply "15 £ per item".
Edit: If you want to dynamically create the Unicode character from its hex string, you can use this:
public static char HexToChar(string hex)
{
return (char)ushort.Parse(hex, System.Globalization.NumberStyles.HexNumber);
}
For example, HexToChar("20AC") will get you the Euro sign.
If you want to do the opposite operation dynamically:
public static string CharToHex(char c)
{
return ((ushort)c).ToString("X4");
}
For example CharToHex('€') will get you "20AC".
The choice of ushort corresponds to the range of possible char values, shown here.
I cant believe this was difficult to find on the internet!
For future developers,if you have the unicode character its easy to do. eg:
C#:
var selectionIndex = txt.SelectionStart;
string copyrightUnicode = "00A9";
int value = int.Parse(copyrightUnicode, System.Globalization.NumberStyles.HexNumber);
string symbol = char.ConvertFromUtf32(value).ToString();
txt.Text = txt.Text.Insert(selectionIndex, symbol);
txt.SelectionStart = selectionIndex + symbol.Length;
VB.Net
Dim selectionIndex = txt.SelectionStart
Dim copyrightUnicode As String = "00A9"
Dim value As Integer = Integer.Parse(copyrightUnicode, System.Globalization.NumberStyles.HexNumber)
Dim symbol As String = Char.ConvertFromUtf32(value).ToString()
txt.Text = txt.Text.Insert(selectionIndex, symbol)
txt.SelectionStart = selectionIndex + symbol.Length

C# Convert Char to Byte (Hex representation)

This seems to be an easy problem but i can't figure out.
I need to convert this character < in byte(hex representation), but if i use
byte b = Convert.ToByte('<');
i get 60 (decimal representation) instead of 3c.
60 == 0x3C.
You already have your correct answer but you're looking at it in the wrong way.
0x is the hexadecimal prefix
3C is 3 x 16 + 12
You could use the BitConverter.ToString method to convert a byte array to hexadecimal string:
string hex = BitConverter.ToString(new byte[] { Convert.ToByte('<') });
or simply:
string hex = Convert.ToByte('<').ToString("x2");
char ch2 = 'Z';
Console.Write("{0:X} ", Convert.ToUInt32(ch2));
get 60 (decimal representation) instead of 3c.
No, you don't get any representation. You get a byte containing the value 60/3c in some internal representation. When you look at it, i.e., when you convert it to a string (explicitly with ToString() or implicitly), you get the decimal representation 60.
Thus, you have to make sure that you explicitly convert the byte to string, specifying the base you want. ToString("x"), for example will convert a number into a hexadecimal representation:
byte b = Convert.ToByte('<');
String hex = b.ToString("x");
You want to convert the numeric value to hex using ToString("x"):
string asHex = b.ToString("x");
However, be aware that you code to convert the "<" character to a byte will work for that particular character, but it won't work for non-ANSI characters (that won't fit in a byte).

Categories

Resources