Reputation: 93
I have a loop let say from 1 to 32. 1 to 32 are decimal in this case. I have to insert the hex value of 1 to 32 in an unsigned char array and then perform send. My code looks like this
char hex[3];
unsigned char hexunsigned[3];
int dec;
int i=0;
do
{
// this is the unsigned char array , i have to insert at 4th pos.
unsigned char writebuffer[8] ={0x01, 0x05, 0x00, 0x20, 0xFF, 0x00, 0x00, 0x00};
// to place the hex value of each point on writeBuffer[3]
dec=i+1;
decimal_hex(dec,hex); //this function returns hex value of corresponding i value.
memcpy(hexunsigned,hex,sizeof(hexunsigned)); //converting char to unsigned char
writebuffer[3]= hexunsigned; //shows the error cannot convert from 'unsigned char [3]' to 'unsigned char'
unsigned short int crc = CRC16(writebuffer, 6); // Calculates the CRC16 of all 8 bytes
writebuffer[6] = ((unsigned char*) &crc)[1];
writebuffer[7] = ((unsigned char*) &crc)[0];
serialObj.send(writebuffer, 8);
//send another packet only after getting the response
DWORD nBytesRead = serialObj.Read(inBuffer, sizeof(inBuffer));
i++;
}while(nBytesRead!=0 && i<32);
so, the line
writebuffer[3]= hexunsigned;
shows the error as cannot convert from 'unsigned char [3]'
to 'unsigned char'
.
how to insert hex unsigned
in writebuffer
array.
when
char hex[3];
int dec;
dec=i+1;
decimal_hex(dec,hex);
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));
is used , it is translating 01(dec) as 31.
I have tried the below code also , it is also translating 01(dec) as 31.
sprintf(hex, "%X", dec);
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));
I think it is treating '1' received at hex variable as ascii and sending hex value of character '1' as 31.
The send function is below:
void serial::send(unsigned char data[], DWORD noOfByte)
{
DWORD dwBytesWrite;
WriteFile(serialHandle, data, noOfByte, &dwBytesWrite, NULL);
}
Upvotes: 0
Views: 3229
Reputation: 405
You can merge the two lines
memcpy(hexunsigned,hex,sizeof(hexunsigned)); //converting char to unsigned char
writebuffer[3]= hexunsigned;
into one:
memcpy(writebuffer+3, hex, 3);</strike>
and the temporary hexunsigned is redundant
--------------------Update line--------------------
Actually when we say hex encoding, we want to use two bytes to represent an original byte, for example
0x33 30 // '3' '0'
represents 0x30
So in you case 0x01~0x20
should be represented as 0x00 01
to 0x02 00
, if you want to use sprintf to convert from dec to hex, you can use as this:
sprintf(hex, "%02X", dec);
memcpy(writebuffer+3, hex, 2);
And your output will be like this "01 05 00 30 31 00 00 00"
for i=1 without CRC16 considered.
Upvotes: 1
Reputation: 7255
hexunsigned must be a unsigned char array, and writebuffer[3] is a unsigned char.
You can not assign a unsigned char to a unsigned char array.
If you want to copy hexunsigned to writebuffer[3] address, use memcpy.
Upvotes: 0