Packed value in C++ or C

1.4k views Asked by At
    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
    };

Where FILE_UPC_KEY_SIZE & FILE_ITEM_KEY_SIZE = 8. Is packed value equivalent to Hex value? How do i store '0123456789012' equivaent decimal calue in the UPC & SKU array? Thanks for all your help.

1

There are 1 answers

7
brad b On

You asked "How do i ...", here's some example code with comments

#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;
}