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];
unsignedchar hexunsigned[3];
int dec;
int i=0;
do
{
// this is the unsigned char array , i have to insert at 4th pos.
unsignedchar 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(writebuffer+3,hex,3);// to insert the converted hex value in 3rd position
unsignedshortint crc = CRC16(writebuffer, 6); // Calculates the CRC16 of all 8 bytes
writebuffer[6] = ((unsignedchar*) &crc)[1];
writebuffer[7] = ((unsignedchar*) &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);
But this code is converting 01(dec) to 31. 01 should be converted to 01 and so on . what can be wrong with the code.
void decimal_hex(int n, char hex[]) /* Function to convert decimal to hexadecimal. */
{
int i=0,rem;
while (n!=0)
{
rem=n%16;
switch(rem)
{
case 10:
hex[i]='A';
break;
case 11:
hex[i]='B';
break;
case 12:
hex[i]='C';
break;
case 13:
hex[i]='D';
break;
case 14:
hex[i]='E';
break;
case 15:
hex[i]='F';
break;
default:
hex[i]=rem+'0';
break;
}
++i;
n/=16;
}
hex[i]='\0';
strrev(hex); /* Reverse string */
}
Walking through the code, in the case of 01 (dec):
decimal_hex will write the ascii character for "1" (0x31) into hex[0]
(Since you've just got one character, after strrev, it remains unchanged)
Remember that writebuffer is an array of unsigned chars, exactly 8 bytes (probably) in length. memcpy will overwrite the 3rd position (counting from 0), with 0x31, the 4th with 0 (from hex[i]='\0'), and some garbage into 5th position.
Regardless, you've only succeeded in replacing 1 by the ascii value of character '1'
Now, I imagine this is what you want, but you have to remember to interpret it that way on the receiving end. You have to be clear that the character "2" is not the value 2 - after all this is what decimal_hex is based on.
If you had tried to convert 32 (dec) for instance, you would have ended up with the string "20" Think of it this way:
All your values are represented by the computer as binary, and hex and decimal values both have the same binary representation. Therefore, what you really need to do is convert your integer value into an array of characters, and copy them in the correct endian order.
What you are actually doing now is converting between integers and ASCII character values, which are not hex values.