I'm sending in a hex representation of a byte through the serial port and I needed to convert it to a byte to use in my application. I've approached it several different ways and it looks like there's got to be an easier way to approach it than the way I have been (and I haven't yet found anything online that resolves this issue). I'm guessing there's probably a simple function that does what I want it to do without 3 or 4 different conversions.
Does anyone have any suggestions on how to approach this?
Essentially, I'm trying to take a string (inString) with value "CE" and store the equivalent in byte form (0xCE or 206) into outByte. Below is what I'm currently working with:
Original Code:
String inString = “CE”
Byte outByte;
outByte = inString.toInt();
printData("outByte: " + String(outByte),serialchan);
Output:
outByte: 0
Additional approaches:
String inString = “CE”
Byte outByte;
char tempchar[2];
String tempstring;
inString.toCharArray(tempchar, 4); // Works with 4, not with 2 for whatever reason
printData("inString: " + String(inString),serialchan);
printData("inString hex: " + String(tempchar),serialchan);
tempstring = "0x" + String(inString);
printData("inString in string hex: " + String(tempstring),serialchan);
outByte = (byte)tempstring.toInt();
printData("outByte: " + String(outByte),serialchan);
Output:
outByte: 0
inString: CE
inString hex: CE
inString in string hex: 0xCE
outByte: 0
I'm expecting outByte to read 206 (I'll convert it to a hex string later, I'm guessing that's pretty straight forward). Like I said, I think I'm close . . . but there just seems like there should be a simple one or two line solution to this. If you have any suggestions, please let me know. Thanks!
strtol. For examplelong val = strtol(inString, NULL, 16);. Or you can usesscanf.Stringto a C-style buffer first with itsgetBytes()method?4and pass the actual size of the buffer available. If it is length4then you pass4to thegetBytes.