View previous topic :: View next topic |
Author |
Message |
aodj
Joined: 20 Dec 2006 Posts: 40 Location: Reading, UK
|
Determining bitsize |
Posted: Fri Apr 27, 2007 2:00 am |
|
|
Is there any way to determine the size, or width, of a variable at runtime?
For example, [in psuedo]
Code: | if(a.bitsize == 8)
{
}
else
{
} |
Thus running one statement if it was 16 bits, and another if it was 8. |
|
|
Pret
Joined: 18 Jul 2006 Posts: 92 Location: Iasi, Romania
|
|
Posted: Fri Apr 27, 2007 2:26 am |
|
|
You meen sizeof ?!
case(sizeof(a))
{
switch 1: /* handle 8bit */ break;
switch 2: /* handle 16bit */ break;
switch 4: /* handle 32bit*/ break;
}
I hope that's what you want... |
|
|
aodj
Joined: 20 Dec 2006 Posts: 40 Location: Reading, UK
|
|
Posted: Fri Apr 27, 2007 3:51 am |
|
|
Ok, thanks, that was exactly what I was looking for.
In addition to the above, is there anyway to pass a variable sized value to a subroutine? For example, normally a subroutine is declared as:
Code: | void fIncrement(int8 v1)
{
} |
This obviously limits the values passed to the routine to being int8's. Is there another way to express this so that v1 can be either 8 bit -or- 16?
Edit: Or would overloading the function be the only way to handle different data types? |
|
|
Pret
Joined: 18 Jul 2006 Posts: 92 Location: Iasi, Romania
|
|
Posted: Fri Apr 27, 2007 7:26 am |
|
|
You cand always pass a pointer to function... using void* as type, bust still you'll have to pass the size as another parameter.
Best thing to do is to define a type. Ex:
Code: | typedef int8 integer;
integer a;
void fIncrement(integer a)
{
int8 x;
// you can do any integer operation
a++;
x = a;
a|=4;
// and so on
}
|
if you want to send it, you can do:
Code: | int8 *ptr;
int8 i;
ptr = &a;
for(i=0; i<sizeof(a); i++)
{
putc(ptr[i]);
}
|
if you want to use printf...
Code: | if(sizeof(a) == 1) printf("a=%u", a); // for 8 bit
else printf("a=%lu", a); // for 16 and 32 bit
|
if you want to change the type for integer, only needed thing to do is to change the basic type from typedef declaration to int16 or int32
Note that this is a compile time operation. Cannot be changed in runtime. |
|
|
Foppie
Joined: 16 Sep 2005 Posts: 138 Location: The Netherlands
|
|
Posted: Fri Apr 27, 2007 7:48 am |
|
|
aodj wrote: | Is there anyway to pass a variable sized value to a subroutine? For example, normally a subroutine is declared as:
Code: | void fIncrement(int8 v1)
{
} |
This obviously limits the values passed to the routine to being int8's. Is there another way to express this so that v1 can be either 8 bit -or- 16? |
if you make it Code: | void fIncrement(int16 v1)
{
} | you can send both int8 as int16 to the function, if you send an int8, the compiler will make a cast to a int16.
hope this helps... |
|
|
|