Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 1 month ago.
byte value instead of ascii in char array
First, I am new to the C language. I cobbled some example code to send some CAN data through the Ethernet port using UDP. Using sprint to fill the buffer, everything works and I send ASCII formatted data. I don't want ASCII though, I want actual byte values sent. So I tried to modify, and cant seem to figure it out.
This seems to work, but sends ASCII data:
sprintf(UDPdata, "%X,%X,%X,%X,%X,%X,%X,%X,%X",can_MsgRx.id,can_MsgRx.data[0],can_MsgRx.data[1],can_MsgRx.data[2],can_MsgRx.data[3],can_MsgRx.data[4],can_MsgRx.data[5],can_MsgRx.data[6],can_MsgRx.data[7]); display.printf("%d",strlen(UDPdata)); //Shows 24 or so bytes, depending on data udp.sendto( UDPdata, strlen(UDPdata), &multicast );
Tried this instead to send byte values, but the char array UDPdata appears to be empty before sending:
UDPdata[0] = (can_MsgRx.id & 0xff000000) >> 24; //can_MsgRx.id is an 32 bit unsigned integer, so mask and shift bits to break it in to 4 bytes UDPdata[1] = (can_MsgRx.id & 0x00ff0000) >> 16; UDPdata[2] = (can_MsgRx.id & 0x0000ff00) >> 8; UDPdata[3] = (can_MsgRx.id & 0x000000ff); for(i=0; i < can_MsgRx.len; i++) { //can_MsgRx.len is the length of the data message (always 8 bytes in this case) UDPdata[4+i] = can_MsgRx.data[i];//can_MsgRx.data is the actual data, a group of 8 bytes } display.printf("%d",strlen(UDPdata)); //Always shows 0 udp.sendto( UDPdata, strlen(UDPdata), &multicast );
The display shows that the length of UDPdata is 0 in the second snippet. In addition, a packet capture shows that the packet is being sent, but it is empty.
Any ideas on how to fill the array with individual byte values and not a string?
Thanks
Sonny
2 Answers
10 years, 1 month ago.
strlen() determines the length of the string by locating the position of the terminating null character. In this snippet, the compiler will add a terminating 0x00 to the ascii characters:
char * mystring="Hello World";
You can test the value of mystring[11], it will be zero.
You are misusing string functions on arrays of arbitrary non-ascii values; the value at UDPdata[0] (or somewhere else) may be zero in the context of your usage, so using strlen() to determine the total length will produce incorrect results.
Instead, use (4+can_MsgRx.len) as the number of bytes to send.
Use putc commands to send bytes with out modification. You also can not get a printf to send 0x00. I use this for UART and SPI interfaces with complete success.
posted by John Johnston 12 Jan 2015