如何在32位处理器上使用一个有符号整数和一个无符号整数来生成带符号的64位整数

时间:2017-04-07 09:49:26

标签: c

在具有32位编译器的32位处理器上,我想使用每个有符号和无符号整数之一来生成64位有符号整数。不使用任何预定义的宏或类型。

1 个答案:

答案 0 :(得分:0)

32-bit compilers will handle 64-bit numbers for you. So its unlikely you actually need this. But I'll bite. On the surface this is a pretty simple problem.

#include <stdint.h>

static inline int64_t make_int64(uint32_t low, int32_t high) {
    return (int64_t)((uint64_t)high << 32) | low;
}

static inline void split_int64(int64_t value, uint32_t *low, int32_t *high) {
    *low = value & 0xFFFFFFFF;
    *high = (int32_t)((uint32_t)(value >> 32));
}

But its always tricky/dangerous mixing signed and unsigned integers. Manually constructing an int also requires you to know how the processor formats them. We'll assume its 2s compliment little endian.

It would be helpful if you gave a full description of your requirements. For example the above example make_int64(0, -1) = -4294967296 but make_int64(1, -1) = -4294967295.

相关问题