String Array to Byte Array

Hi,

I am very new to programming and I have been searching for example for hours on how to convert a string array to a byte array retaining the same hex value.

I know there are lots of post and reply on similiar topic but I couldn't get my head around it, and I might not explained my question correctly, so below is what I try to achieve, I would appreciate some help please.

I would like to convert something like this

String TEST_ON = "0x02 0x11 0x90 0x6A 0x00 0x01 0x02 0x00 0x01 0xFE 0x93";

To

byte TEST_ON[] = {0x02, 0x11, 0x90, 0x6A, 0x00, 0x01, 0x02, 0x00, 0x01, 0xFE, 0x93};

so that I can use Serial.write( TEST_ON, sizeof(TEST_ON) ); to send the exact hex byte like following to serial port

02 11 90 6A 00 01 02 00 01 FE 93

THANK YOU

Did you mean to leave a blank space between the hex numbers? If so, that space is a X20, not a blank. So your Serial.write will send 012011209020.....
Paul

Thanks Paul, but no, I don't meant to leave a blank space, but I would like to send hex value in byte instead of ASCII on serial port.

I know I can send byte using serial.write, however serial.write do not take string. so I was hopping I can somehow convert above string to byte array then cast it into serial using serial.write

this is what I wish to see in serial port in HEX format
image

Where is your String coming from? What is building that String?

Part of the string concate from prefix define in code
other part it is build by sprinf and strcy using data from rtc and caculated CRC .
it was concate as a string from different code / source. like below

sprintf (SEC, "%02X", myRTC.seconds);
strcpy(TEST_ON, PREFIX2); // Prefix 0211906A
strcat(TEST_ON, " 0x");
strcat(TEST_ON, MIN);
strcat(CON2, " 0x");
strcat(CON2, CRC1);

I was going to reserve this string as record for future use (save in SDcard)
but first priority is to find out if it is possible send it to serial port as byte in hex rather than ASCII.
Thanks

What does the string actually look like? Are the hex numbers separated by a space?

AFAIK anything transmitted over serial port is bytes - so instead of sending the bytes in a string, why not send them directly? That will save the step of first collecting them in a string and then writing the string to serial.

That means:
1. Your input is:
"0211906A0001020001FE93" //ASCII codes characters

2. You want to see the above string as:
02 11 90 6A 00 01 02 00 01 FE 93 //as byes in hex-base

Solution:
See this thread (Post-15) for a smaller string and then apply that for your long string.

Hi GolamMostafa,

Thank you for pointing me to the other post. I managed to progress with the example given by @johnwasser (Thanks johnwasser)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.