I'm looking to build a binary string that consists of hex values... I've learned sprintf is not the correct way to accomplish this. I've got a real simple gui to collect configuration settings that need to be sent a device. The values can be signed and will always be numerical. I have a set of values like:
#define PKTHEAD 0xA5
#define VALONE 0xA0
#define VALTWO 0xA1
#define VALTHREE 0xA2
#define PKTTAIL 0x5A
signed int val1 = 10000; //0x2710
signed int val2 = -84; //0xFFAC
signed int val3 = -175001 //0xFFFD5467
My end goal is to have a packet that would resemble "PKTHEAD|PKTHEAD|PKTHEAD|VALONE|val1|VALTWO|val2|VALTHREE|val3|PKTTAIL|PKTTAIL|PKTTAIL", and the hex representation would be A5A5A5A000002710A1FFFFFFACA2FFFD54675A5A5A.
Right now I'm doing this:
int main(int argc, char *argv[])
{
int numBytes = 10;
signed char *tmp;
signed char *pyld;
pyld = calloc(numBytes, sizeof(char));
signed int val1 = 10000; //0x2710
signed int val2 = -84; //0xFFAC
signed int val3 = -175001 //0xFFFD5467
tmp = pyld;
*(tmp + (numBytes - 1)) = DACHEAD;
*(tmp + (numBytes - 2)) = DACHEAD;
*(tmp + (numBytes - 3)) = DACHEAD;
*(tmp + (numBytes - 4)) = VALONE;
*(tmp + (numBytes - 5)) = val1;
printf("payload = %hhx%hhx%hhx%hhx%hx%hx%hhx%hx\n", pyld[9], pyld[8], pyld[7], pyld[6], pyld[5], pyld[4], pyld[3], pyld[2], pyld[1], pyld[0]);
}
The output is: "payload = a5a5a5a0100a1ffac"
My val1 value is incorrect and I'm wondering if there is a better way to compose this packet. Should I be doing bit shifts instead?
Any help is greatly appreciated.
Thanks!