Home > Mobile >  Struct initialisation with large integer
Struct initialisation with large integer

Time:05-24

So I have the following struct:

typedef struct int64 {
    unsigned char value[8];
} int64;

Which I an using to represent a 64 bit integer (I know this exists in stdint.h but I thought it could be a good exercise to try and write it myself, and I plan to use this format for much larger integers). My question is there any way that I could initialize this struct with a binary string or an overlarge integer, something like:

int64 number = 0b1000000000000000000000000000000000000000000000000000000000011001

// Or

int64 number = 1231823812738123878;  // Or something larger than 2^32

Thanks for any help you can give me :)

CodePudding user response:

You'd have to break it up byte by byte, since the struct contains an array of bytes:

int64 number = { { 0b10000000, 0b00000000, 0b00000000, 0b00000000, 
                   0b00000000, 0b00000000, 0b00000000, 0b00011001 } };

You can compress this using hex constants instead of binary constants:

int64 number = { { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x19 } };

CodePudding user response:

For a 64-bit number, you could get away with a macro:

#if USE_BIG_ENDIAN
#define INIT64(x) { (((x)|0ULL)>>56)&255, (((x)|0ULL)>>48)&255, \
                    (((x)|0ULL)>>40)&255, (((x)|0ULL)>>32)&255, \
                    (((x)|0ULL)>>24)&255, (((x)|0ULL)>>16)&255, \
                    (((x)|0ULL)>> 8)&255, (((x)|0ULL)>> 0)&255 }
#else
#define INIT64(x) { (((x)|0ULL)>> 0)&255, (((x)|0ULL)>> 8)&255, \
                    (((x)|0ULL)>>16)&255, (((x)|0ULL)>>24)&255, \
                    (((x)|0ULL)>>32)&255, (((x)|0ULL)>>40)&255, \
                    (((x)|0ULL)>>48)&255, (((x)|0ULL)>>56)&255 }
#endif

int64 number0 = INIT64(0);
int64 number1 = INIT64(0b1000000000000000000000000000000000000000000000000000000000011001);
int64 number2 = INIT64(1231823812738123878);

This approach alas won't work for larger types. Converting at runtime from a string representation is a classic solution. You could also preprocess your source code with a utility that substitutes an appropriate syntax, such as BIGNUM(x) with the equivalent initializer.

  •  Tags:  
  • c
  • Related