c++ - C++ 或 C 中的打包值

标签 c++ c hex packed

    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”等效小数?感谢你的帮助。

最佳答案

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

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

关于c++ - C++ 或 C 中的打包值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20339118/

相关文章:

c - 错误 : libtool - while compiling an MPI program

将未知的十六进制数字转换为经度和纬度

c++ - Qt QBuffer写入的字节无法读取

c++ - 查找数组中的最大值 C++

c - C 中的简化粗俗分数

java - 将十六进制字符串转换为字节中的二进制字符串会抛出 NumberFormatException

java - android 将十六进制转换为字符

c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?

c++ - 关于CRITICAL_SECTION的使用问题

c++ - 这个浮点平方根近似是如何工作的?