0

我有一个 8 字节的计数器,我正在尝试增加它。我稍后想将其转换为 unsigned long long 值。但是转换后的值会抛出错误。这是一些字节序问题还是做错了?请指教。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef unsigned          char uint8_t;
typedef unsigned short     int uint16_t;
typedef unsigned           int uint32_t;

#define COUNTER_LENGTH 8

typedef struct {
    uint8_t data[8];
}count_t;

static void incrementCtr(count_t* count) {
    int i;
    for (i = sizeof(count->data) - 1; i >= 0; --i) {
        if (++count->data[i] != 0) {
            break;
        }
    }
}

int main(int argc, char *argv[]){

    count_t count;
    count_t *counter;
    counter = &count;
    memset(counter ,0,sizeof(*counter));

    incrementCtr(counter);
    int i;
    for (i = 0; i < COUNTER_LENGTH; i++){
        printf("counter->data[%d] = %02X\n", i, counter->data[i]);
    }

    unsigned long long  aa = 0;
    int m;
    for(m = 0; m< COUNTER_LENGTH; m++){
        aa = aa |(counter->data[m]<< m*8);
    }
    printf("aa = %llu\n", aa);
    return 0;
}
4

1 回答 1

1

Huh?

If you're certain that the unsigned long long is big enough, then why are you bothering with the manual implementation? Why not just use an unsigned long long variable?

There's some brokenness in your loop; the expression (counter->data[m] << m * 8) does not have type unsigned long long so will likely drop a lot of bits.

Use something like this:

for(m = 0; m < COUNTER_LENGTH; ++m)
{
  a <<= 8;
  a |= counter->data[m];
}

The above should also be endian-safe; it always OR:s in the most significant byte first (as determined by the counter representation).

于 2013-06-04T09:42:07.800 回答