Xynixme
Xynixme

Reputation: 51

How can a 32-bit structure represent a negative 64-bit value?

In a 32-bit C programming environment without any built-in native 64-bit support, but some parts of the operating system API's do support 64-bit numbers, I have to represent a negative value (range -8192 upto and including -1). Presumably I have to do the maths myself.

typedef struct _LONGLONG {ULONG lo;LONG hi} LONGLONG;
LONGLONG x;

How can I assign such a negative value to x.lo and x.hi, and (less important) perhaps how can I verify it's the right number?

I've read about "What's wrong with quadpart?", but apparently there's no such thing available.

Upvotes: 0

Views: 276

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222724

Bits represent values only according to some type scheme. The question does not state what scheme is used to make the bits in lo and hi represent values. For the purposes of this answer, we will suppose:

  • LONG hi is a 32-bit two’s complement integer.
  • ULONG lo is a 32-bit unsigned integer.
  • The API using this LONGLONG structure interprets lo and hi as a 64-bit two’s complement number formed with the bits of hi as the high 32 bits of the 64-bit number and the bits of low as the low 32 bits.

In this case, if n is a value in [−8192, −1], the upper 32 bits of a 64-bit two’s complement representation are all ones, and the lower 32 bits are the same as the 32 bits of a 32-bit two’s complement representation of n. Therefore, the desired bit patterns of the LONGLONG x can be set with:

x.hi = -1;
x.lo = n;

Note that, since x.lo is unsigned, the assignment x.lo = n will convert the signed n to unsigned. This conversion will be done by wrapping modulo 232, and the resulting 32-bit unsigned value for x.lo has the same bit pattern as the 32-bit two’s complement value for n, so the desired result is achieved.

Upvotes: 1

Related Questions