I started struggling with something I didn't think would be that complicated, so I would really appreciate some advice. I will tell you my situation.
I write data to a device/card. The writing procedure is easy and goes usually like this:
unsigned char sendBuffer[32];
sendBuffer[0] = headerInfo;
sendBuffer[1] = headerInfo;
sendBuffer[2] = data[0];
sendBuffer[3] = data[1];
...
sendBuffer[17] = data[15];
The
data
I
write is usually 16 bytes, or multiple of 16. So, storing is easy, I just call:
SendData(sendBuffer, length)
, and done, data is stored.
1) My question is say I want to store now integer 517 on the card - what data shall I send to the device? How to embed it in the
sendBuffer
array?
2) Similarly. Say I want to send string "Hello world xyz" to the device. How to embed it in the
sendBuffer
?
Some highlights. I am the receiver end. I will be reading the data back. And also depending where I stored it I may in advance know whether it is an int or string.
I also don't have endianness issues.
Example
---------
Below I will just provide working example which manages to write and read 16 byte HEX strings and hope this will be helpful to you to answer my questions better.
Say I want to write this string: "
00000000000000000000AABBEEAABBEE
"
We convert it to byte array:
for(int i=0,m=0; i < size; i+=2,m++)
{
char ch1, ch2;
ch1=(char)str[i];
ch2=(char)str[i+1];
int dig1, dig2;
if(isdigit(ch1)) dig1 = ch1 - '0';
else if(ch1>='A' && ch1<='F') dig1 = ch1 - 'A' + 10;
else if(ch1>='a' && ch1<='f') dig1 = ch1 - 'a' + 10;
if(isdigit(ch2)) dig2 = ch2 - '0';
else if(ch2>='A' && ch2<='F') dig2 = ch2 - 'A' + 10;
else if(ch2>='a' && ch2<='f') dig2 = ch2 - 'a' + 10;
array1[m] = (char)(dig1*16 + dig2);
}
Now, we copy this byte array
array1
to the
sendBuffer
as above, e.g.,
for(int i=0;i<16;i++)
sendBuff[i]=array1[i];
and done we call
send
command as I mentioned before.
Reading is also easy, I call:
Receive(receiveBuffer)
and now
receiveBuffer
contains the byte array I wrote previously. Then I need to convert it back to hex like this:
for(k=0;k<16;k++)
{
data[k*2]=hexval[((receiveBuffer[k]>>4)&0xF)];
data[(k*2)+1]=hexval[receiveBuffer[k]&0x0F];
}
And done,
data
now contains my initial hex string: "00000000000000000000AABBEEAABBEE".