c++ - Dynamic Integer Size: int64_t, int32_t, uint32_t, etc -


i programming app allows user select bit-size of integer storage , math it. can select 8, 16, 32, or 64 bit storage signed or unsigned. set , changed @ runtime, , app math given type.

user interaction example:

  • enter 16 bit mode
  • type 5c
  • press plus
  • type 2a
  • press evaluate
    • return { value1.getsigned16() + value2.getsigned16(); }

i avoid programming 8 cases each operator. figure pointer or function-pointer might work this. evaluate method doesn't care size of integer i'm using long both same. problem can't figure out how implement this, pointers care kind of variable returned. considered using generic pointer doesn't me when need dereference, still need 8 cases.

value1.getpropersize() + value2.getpropersize();  // * won't work int* getpropersize() {     if (size == 16) return (int16_t)storagevalue;     if (size == 32) return (int32_t)storagevalue;     // etc... } 

any thoughts or suggestions on attacking problem appreciated.

you cannot have "arbitrary" return value type function. if want return different sized integer, there few ways it: union, function overloads, templates (which cover function overloads), or (and cringe type this) void* return value.

base on you've asked, union best fit:

struct myinteger {     uint8_t intsize;     union     {         int8_t  int8;         int16_t int16;         int32_t int32;         int64_t int64;     } intvalue; };  myinteger getpropersize() {     myinteger result;     if (size == 8)     {         result.intsize = 8;         result.intvalue.int8 = somevalue;     }     // ...     return result; } 

the size of structure minimum of 72 bits (excluding padding , alignment issues), return int64_t , cover every smaller integer size.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -