C# char into int bigger than 256 - c#

i need to convert some char to int value but bigger than 256. This is my function to convert int to char. I need reverse it
public static string chr(int number)
{
return ((char)number).ToString();
}
This function doesnt work - its returning only 0-256, ord(chr(i))==i
public static int ord(string str)
{
return Encoding.Unicode.GetBytes(str)[0];
}

The problem is that your ord function truncates the character of the string to the first byte, as interpreted by UNICODE encoding. This expression
Encoding.Unicode.GetBytes(str)[0]
// ^^^
returns the initial element of a byte array, so it is bound to stay within the 0..255 range.
You can fix your ord method as follows:
public static int Ord(string str) {
var bytes = Encoding.Unicode.GetBytes(str);
return BitConverter.ToChar(bytes, 0);
}
Demo

Since you don't care much about encodings and you directly cast an int to a char in your chr() function, then why dont you simply try the other way around?
Console.WriteLine((int)'\x1033');
Console.WriteLine((char)(int)("\x1033"[0]) == '\x1033');
Console.WriteLine(((char)0x1033) == '\x1033');

char is 2 bytes long (UTF-16 encoding) in C#
char c1; // TODO initialize me
int i = System.Convert.ToInt32(c1); // could be greater than 255
char c2 = System.Convert.ToChar(i); // c2 == c1
System.Convert on MSDN : https://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx

Characters and bytes are not the same thing in C#. The conversion between char and int is a simple one: (char)intValue or (int)myString[x].

Related

How to convert a MAC address from string to unsigned int

A MAC address (Wikipedia article) is typically formatted in the form of 6 hexadecimal numbers separated by a semicolon, like 14:10:9F:D4:04:1A.
In C#, it can be passed around as a string, while some libraries manipulate these as a UInt64 or ulong.
Question
What are the relationship between the string, hex representation, ulong, and how can I go from one to the other?
MAC Address is HEX
As correctly described here:
The MAC address is very nearly a hex string. In fact, if you remove the ':' characters, you have a hex string.
14:10:9F:D4:04:1A literally means 0x14109FD4041A, only easier to read.
string to UInt64 and back
A MAC address is made up of 6 bytes, 48 bits, fitting in an UInt64 with 2 bytes to spare. Leaving out the MSB vs. LSB ordering complication, you can use the 2 methods below:
Format into a string
using System;
using System.Linq;
public static string MAC802DOT3(ulong macAddress)
{
return string.Join(":",
BitConverter.GetBytes(macAddress).Reverse()
.Select(b => b.ToString("X2"))).Substring(6);
}
// usage: var s = MAC802DOT3(0x14109fd4041a);
// var s = MAC802DOT3(22061633504282);
// s becomes "14:10:9F:D4:04:1A"
Convert to an integer
public static ulong MAC802DOT3(string macAddress)
{
string hex = macAddress.Replace(":", "");
return Convert.ToUInt64(hex, 16);
}
// usage: var m = MAC802DOT3("14:10:9F:D4:04:1A");
// m becomes 22061633504282 (0x14109fd4041a)

How can I declare hex vars in c#

how can I declare 2 bytes hex in c# and compare in a "if" like this java code:
public static final int MSG_GENERAL_RESPONSE = 0x8001;
int type = buf.readUnsignedShort();
if (type == MSG_TERMINAL_REGISTER) {
}
c# 2 bytes is not possible in c#? I tried and havent found a way. How can I translate this code to c#?
It would be OK to use int in your case (that is a signed 32-bit integer type), but it looks like ushort (unsigned 16-bit) is more precise here:
public const ushort MSG_GENERAL_RESPONSE = 0x8001;
// ...
ushort type = buf.readUnsignedShort();
if (type == MSG_TERMINAL_REGISTER) {
}
Note that if you want to give a negative literal in hexadecimal (with the convention that when the leading digit is from 8 through F, then it is two's complement), you need the following clumsy notation:
// negative:
public const short MSG_GENERAL_RESPONSE = unchecked((short)0x8001);
You cannot use final in C#. For a class member, you can use static readonly or const (the latter is implicitly static). For a local variable you can use const.

Converting C# to VB - Private String Statement

I have been given some C# code which defined some Private String but I am not sure what it is doing honestly and need to convert into VB for my Project but wandered if someone might take a moment to explain and possible provide a conversion?
private string GetChecksum(StringBuilder buf)
{
// calculate checksum of message
uint sum = 0;
for (int i = 0; i < buf.Length; i++)
{
sum += (char)buf[i];
}
return string.Format("{0:X04}", sum);
}
The part with private string ... is the method declaration. C#'s
Accessibility ReturnType MethodName(Type paramName)
translates to
Accessibility Function MethodName(paramName As Type) As ReturnType
Private Function GetChecksum(buf As StringBuilder) As String
'calculate checksum of message
Dim sum As UInteger = 0
For i As Integer = 0 To buf.Length - 1
sum += CChar(buf(i))
Next
Return String.Format("{0:X04}", sum)
End Function
What the function does is adds up the ASCII values of each character in the string (stored in a 2-byte char without overflow checking) and return the result as a string - the 4-character hexadecimal representation of the 2-byte result.
A checksum is used to detect data errors; if two strings yield different checksums then they cannot be equal. Two strings that give the same checksum, however, are non necessarily equal, so it cannot be used to verify equality.

How to display text being held in a int variable?

My variable holds some text but is currently being stored as an int (the class used reads the bytes at a memory address and converts to int. Variable.ToString just displays the decimal representation, but doesn't encode it to readable text, or in other words, I would now like to convert the data from int to string with ascii encoding or something.
Here is a demo (based on our Q+A above).
Note: Settings a string with the null terminator as a test, then encoding it into ASCII bytes, then using unsafe (you will need to allow that in Build Option in project properties), itearte through each byte and convert it until 0x0 is reached.
private void button1_Click(object sender, EventArgs e)
{
var ok = "OK" + (char)0;
var ascii = Encoding.ASCII;
var bin = ascii.GetBytes( ok );
var sb = new StringBuilder();
unsafe
{
fixed (byte* p = bin)
{
byte b = 1;
var i = 0;
while (b != 0)
{
b = p[i];
if (b != 0) sb.Append( ascii.GetString( new[] {b} ) );
i++;
}
}
}
Console.WriteLine(sb);
}
Note the FIXED statement, this is required managed strings/arrayts etc are not guaranteed to be statically placed in memory - this ensures it during that section.
assuming an int variable
int x=10;
you can convert this into string as
string strX = x.ToString();
Try this
string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
Console.WriteLine(b);
}
Int32.ToString() has an overload that takes a format string. Take a look at the available format strings and use one of those.
Judging by your previous question, the int you have is (probably) a pointer to the string. Depending on whether the data at the pointer is chars or bytes, do one of these to get your string:
var s = new string((char*)myInt);
var s = new string((sbyte*)myInt);
OK. If you variable is a pointer, then Tim is pointing you in the right direction (assuming it is an address and not an offset from an address - in which case you will need the start address to offset from).
If, on the other hand, your variable contains four encoded ascii characters (of a byte each), then you need to split to bytes and convert each byte to a character. Something like this Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertTo(myUint, typeof(string))); from Here - MSDN ByteConverter

Is there something like java's Character.digit(char ch, int radix) in c#?

Character.digit(char ch, int radix)
Returns the numeric value of the character ch in the specified radix.
Is there an equivalent function in c#?
I don't know of a direct equivalent
The closest match I can find is
Convert.ToInt32(string s, int baseFrom);
So you could convert your char to string then pass it in to the above function to get the int32 or Int16 or Byte or however you want to handle it :
char c = 'F';
int digit = Convert.ToInt32(c.ToString(),16);
Note - Convert will throw a FormatException if the char isn't a digit
If you work with hex characters you can do:
if (System.Uri.IsHexDigit(c)) {
int v = System.Uri.FromHex(c);
}

Categories