简体   繁体   English

C#将十六进制字符串转换为字节

[英]C# Convert Hex string to byte

Little bit stuck on this, I have a var called PORTBhex holding a value in the range 0x00 to 0x3F which is written to an external device via USB. 有点卡住了,我有一个名为PORTBhex的变量,其值在0x00到0x3F范围内,并通过USB写入外部设备。 The problem I am having is getting the value into this bit of code: 我遇到的问题是将值添加到以下代码中:

public bool PORTBwrite()
        {
            Byte[] outputBuffer = new Byte[65];
            outputBuffer[0] = 0;
            outputBuffer[1] = 0x00; //Command tells PIC18F4550 we want to write a byte

            outputBuffer[0] = 0;
             //Must be set to 0

            outputBuffer[2] = IO.PORTBhex;
                 //Hex value 0x00 - 0x3F to write to PORTB
                 //above line gives the error cannot implicity convert string - byte
                 //IO.PORTBhex is returned from the code in second snippet

            if (writeRawReportToDevice(outputBuffer))
             {
                 return true; //command completed OK

             }else{

                 return false; //command failed .... error stuff goes here

             }
        }

Now the problem is the value i have is an integer that is converted to hex using: 现在的问题是我拥有的值是一个整数,可以使用以下方式将其转换为十六进制:

 public static string ToHex(this int value)
{
    return string.Format("0x{0:X}", value);
}

The value starts off as an integer and is converted to hex however I cannot use the converted value as its of the wrong type I am getting Cannot implicitly convert type 'string' to 'byte'. 该值以整数开头并转换为十六进制,但是我无法使用转换后的值作为错误类型,因此无法将类型'string'隐式转换为'byte'。

Any idea what I can do to get around this please? 知道我能做什么来解决这个问题吗?

Thanks 谢谢

EDIT: 编辑:

I think I might have poorly described what I'm trying to achieve, I have an int variable holding a value in the range 0-255 which I have to convert to Hex which must be formatted to be in the range 0x00 to 0xFF and then set outputBuffer[2] to that value to send to the microcontroller. 我想我可能没有很好地描述我要实现的目标,我有一个int变量,其值在0-255范围内,我必须将其转换为十六进制,必须将其格式设置为0x00至0xFF,然后将outputBuffer [2]设置为该值以发送到微控制器。

The integer var has some maths performed on it before it needs to be converted so i cannot solely use byte vars and has to be converted to a hex byte afterwards. 整数var在需要转换之前已经执行了一些数学运算,因此我不能只使用字节vars,之后必须转换为十六进制字节。 Thanks 谢谢

To solution is to change PORTBhex to be of type byte and don't use that ToHex method at all: 解决方案是将PORTBhex更改为byte类型,并且根本不使用该ToHex方法:

Instead of IO.PORTBhex = ToHex(yourIntValue) use this: 而不是IO.PORTBhex = ToHex(yourIntValue)使用此:

IO.PORTBhex = checked((byte)yourIntValue);

It would be even better if you could make yourIntValue to be of type byte , too. 如果您也可以将yourIntValue也设置为byte类型,那会更好。

outputBuffer[2] = Convert.ToByte(IO.PORTBhex, 16);

尽管我个人可能会一开始尝试避免使用字符串,而只存储byte

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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