Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A letter in a byte? C#

I have an imported C++ method that receives a byte parameter, but according to the documentation, I can send a letter to that parameter, this is the C++ and C# method:

int WINAPI Sys_InitType(HID_DEVICE device, BYTE type)

public static extern int Sys_InitType(IntPtr device, byte type);

This causes me a syntax error in C#, how do I send a letter in that parameter?

My code (A bit random):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//CRASHES
byte random = Convert.ToByte("A");
_ = RFIDReader.Sys_SetAntenna(g_hDevice, 0);
int lol = RFIDReader.Sys_InitType(g_hDevice, random);
_ = RFIDReader.Sys_SetAntenna(g_hDevice, 1);
CError.Text = lol.ToString();

Documentation of the method

>Solution :

Convert.ToByte(string); doesn’t do what you think it does, according to the documentation

Converts the specified string representation of a number to an equivalent 8-bit unsigned integer.

This would work byte random = Conver.ToByte("52"); which will return the byte 52.

See here:

https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobyte?view=net-6.0#system-convert-tobyte(system-string)

As was pointed out in the comment already, you will have to use character instead of string, so either this

byte random = Convert.ToByte('A');

or a simple cast to byte

byte random = (byte)'A'

In case it is unknown to you, which I didn’t assume, a byte can only contain values of the range 0 – 255, while a character can contain everything within the specs of UTF-16.

So this will not work

byte random = Convert.ToByte('\u4542');

And result in the error:

Value was either too large or too small for an unsigned byte.

https://dotnetfiddle.net/anjxt5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading