简体   繁体   中英

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):

//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();

方法的文档

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM