0
    struct FILE_UPC_RECORD
    {
     char UPC[FILE_UPC_KEY_SIZE];// packed up to 16 digits right justified and zero filled
                               // possibilities are:
                               // 1. 12-digit UPC w/2 leading 0's
                               // 2. 13-digit EAN w/1 leading 0
                               // 3. 14-digit EAN
        char SKU[FILE_ITEM_KEY_SIZE];  // packed, 0000ssssssssssss
    };

其中 FILE_UPC_KEY_SIZE & FILE_ITEM_KEY_SIZE = 8。打包值是否等同于十六进制值?如何在 UPC 和 SKU 数组中存储“0123456789012”等效十进制值?感谢你的帮助。

4

1 回答 1

1

您问“我如何……”,这是一些带有注释的示例代码

#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;
}
于 2013-12-03T17:43:10.847 回答