Re: Variables of N bits in size
Re: Variables of N bits in size
- Subject: Re: Variables of N bits in size
- From: Nat! <email@hidden>
- Date: Thu, 24 May 2001 22:13:39 +0200
Am Donnerstag, 24. Mai 2001 um 18:13 schrieb Ken Tabb:
Hi,
what's the most Obj-C friendly way of defining object sizes in bits, for
instance if I want MyObject instances to be 1 bit long? Are ANSI C
bit-field concepts wrapped in C structs still the preferred method in
Obj-C or is there a 'better' way?
Thanks in advance,
Ken
Hi Ken
1 bit long object instances do not make much sense in Obj-C, because
every Obj-C instance has an 32 bit isa pointer prepended. For malloc
alignment and malloc overhead (size, next block etc) that would
translate into probably about 16 bytes per instance [due to memory
alignment you could get an int sized object as well...]
For bitsize instance variables (lots of them then), you use regular C-
bitfields.
If you want to optimize for size, because you are allocating lots of
them bits (like millions), you could write a wrapper class to handle
those bits and deal with the individual bits through that, which gives
you a small memory footprint and slightly better OO design.
You could write your code in as code of an objective C class (Foo),
that accesses an external BitStorage instance like this.
@implementation FooBase
...
- (void) actOnBit:(unsigned int) n
withBitStorage:(BitStorage *) storage
{
NSLog( @"got a bit: %u", [storage bit:n]);
}
...
@end
and have BitStorage defined like this
@implementation BitStorage
...
- (id) initWithBitNo:(unsigned int) n
{
...
size = (n + 7 ) >> 3
buf = malloc( size);
memset( buf, 0, size);
...
}
- (void) setBit:(unsigned int) x
{
buf[ x >> 3] |= 1 << (x & 0x7);
}
- (void) clearBit:(unsigned int) x
{
buf[ x >> 3] &= ~(1 << (x & 0x7));
}
- (BOOL) bit:(unsigned int) x
{
return( (buf[ x >> 3] & (1 << (x & 0x7))) ? YES : NO; // really
lame :)
}
...
@end
That's insane to do it in my opinion, but doable anyway, but because of
the missing type info, it doesn't buy you anything. I'd just go for C in
this case.
Nat!
P.S: coded with 2l Fiege Pils in belly - so it might not be all that bug
free :)