您问“我如何……”,这是一些带有注释的示例代码
#include <stdio.h>
#include <stdint.h>
int main(int argc, const char * argv[])
{
int i, newSize;
// Treat the result packed data as unsigned char (i.e., not a string so not
// NULL terminated)
uint8_t upc[8];
uint8_t *destPtr;
// Assume input is a char string (which will be NULL terminated)
char newUPC[] = "0123456789012";
char *srcPtr;
// -1 to remove the string null terminator
// /2 to pack 2 decimal values into each byte
newSize = (sizeof(newUPC) - 1) / 2;
// Work from the back to the front
// -1 because we count from 0
// -1 to skip the string null terminator from the input string
destPtr = upc + (sizeof(upc) - 1);
srcPtr = newUPC + (sizeof(newUPC) - 1 - 1);
// Now pack two decimal values into each byte.
// Pointers are decremented on individual lines for clarity but could
// be combined with the lines above.
for (i = 0; i < newSize; i++)
{
*destPtr = *srcPtr - '0';
srcPtr--;
*destPtr += (*srcPtr - '0') << 4;
srcPtr--;
destPtr--;
}
// If input was an odd lenght handle last value
if ( (newSize * 2) < (sizeof(newUPC) - 1) )
{
*destPtr = *srcPtr - '0';
destPtr--;
i++;
}
// Fill in leading zeros
while (i < sizeof(upc))
{
*destPtr = 0x00;
destPtr--;
i++;
}
// Print the hex output for validation.
for (i = 0; i < sizeof(upc); i++)
{
printf("0x%02x ", upc[i]);
}
printf("\n");
return 0;
}