I think using scanf() is often an H-bomb-to-kill-an-ant. It can do a lot of things, but programs often use only a small fraction of its utility, resulting in a program that's bigger than it might be. Try these edits to your code:
byte b[4] = {0x13, 0xAB, 0xF2, 0xC1}; // Make it clear they are hex numbers
void setup() {
Serial.begin(9600);
for (int i = 0; i < 4; i++)
{
Serial.print(b[i], HEX); // You need to subscript the array
Serial.print(", ");
}
}
void loop() {
}
Agreed, sscanf is overkill, but if it gets you further down the road quicker, why not?
Knowing that it's bloated, you can optimise later if necessary.
Not sure I agree with you this time. The "why not?" answer is: Teaching shortcuts at the outset usually perpetuates bad coding habits down the road. Besides, I really don't see how it gets you down the road faster. Once you see the mistakes (I did forget about the mangling that the italics did), I thinks it's faster to write it without sscanf(). As to the code size, my version takes 1990 bytes while the sscanf() version takes 3880; almost twice as big. To me, this small rewrite isn't an optimization, it just takes advantage of what's already in place (e.g., defining things correctly and using the Serial object) plus it avoids defining a char array that really isn't needed.
The good news is that the OP can choose for himself. We each demonstrated a tool that he can now hang on his belt...more tools is good. After all, if the only tool you have is a hammer, it's not too surprising that all problems look like a nail.
econjack, I think you both miss the point of the TS. The printing isn't the problem but "converting" it to the array of bytes. Because he receives a string.
Mr. econjack, (0x13) it works when i enter constant value, but in my case the value is received serialy.
Mr. AWOL, the received string contain extra info also (received string form: Cmd_DEL_13ABF2C1), so is the sscanf still work?!
Mr. septillion, no the printing is not my goal, my goal is the conversion itself because also I need to do a compare it with another bytes array, in addition Mr. septillion, what this (ant) do to kill him with nuclear bomb?!!!
It's a bomb OK, the format specifier should be "%2cx".
Sorry.
Look, guys, I know it's sledgehammer, and if I were chasing the bytes, I'd've coded it as nibble-by-nibble explicit conversion, but I'm trying to get the guy moving.
Yes, sscanf will still work, it just needs a little more work.
Mr. guix I try your suggestion code in reply #12
it convert the string:"13ABF2C1" to: 00 AB F2 C1
as you see there is a bug in the beginning, why this bug?!
also I see this way is complex, is there simplest way?!
sorry the buy was in my test code!!!
I optimize the function to be as in the reply #20
Mr. econjack, I try your suggestion code in reply #17
the output is: 13, CB, F2, C1,
while the msg was: "13abf2c1"
the 3rd digit is 'a' and convert to 'C'?!!!
Note that, when change the input string to upper case the output became true