Tom Poulton
Tom Poulton

Reputation: 147

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. 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'.

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.

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. Thanks

Upvotes: 1

Views: 4494

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064234

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

Although personally I'd probably try to avoid strings here in the first place, and just store the byte

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

To solution is to change PORTBhex to be of type byte and don't use that ToHex method at all:

Instead of IO.PORTBhex = ToHex(yourIntValue) use this:

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

It would be even better if you could make yourIntValue to be of type byte, too.

Upvotes: 1

Related Questions