c - 从数组进行简单的 unsigned long long 转换

标签 c bit-manipulation

我有一个 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;
}

最佳答案

嗯?

如果您确定unsigned long long已经足够大了,那你为什么还要费心去手动实现呢?为什么不直接使用 unsigned long long变量?

你的循环中有一些破损;表达式(counter->data[m] << m * 8)没有类型 unsigned long long因此可能会丢失很多位。

使用这样的东西:

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

以上内容也应该是字节序安全的;它总是 OR:s 首先在最高有效字节中(由 counter 表示法确定)。

关于c - 从数组进行简单的 unsigned long long 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16914450/

相关文章:

c++ - (n & m) <= m 总是正确的吗?

matlab - eps() 在 MATLAB 中是如何计算的?

Java如何从udp数据包中的Sint64解析UTC

c - 将 c 代码片段翻译为伪代码

将字符串复制到 malloc 的字符串数组

c - 如果分配失败,我应该手动调用销毁还是释放成员

c++ - 了解负数并转换它们

比较 C 中单个输入中的多个字符串

c - 实模式内核的 16 位 C 代码

c - 在 C 或 CUDA 中使用 << 求幂