[英]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:我有一个接收字节参数的导入 C++ 方法,但根据文档,我可以向该参数发送一封信,这是 C++ 和 C# 方法:
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?这导致我在 C# 中出现语法错误,如何在该参数中发送字母?
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.将数字的指定字符串表示形式转换为等效的 8 位无符号整数。
This would work byte random = Conver.ToByte("52");
这将起作用byte random = Conver.ToByte("52");
which will return the byte
52
.这将返回byte
52
。
See here:看这里:
https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobyte?view=net-6.0#system-convert-tobyte(system-string) 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.如果您不知道,我没有假设,一个字节只能包含 0 - 255 范围内的值,而一个字符可以包含 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 https://dotnetfiddle.net/anjxt5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.