I'm just starting learning C, and I need some help with an array
char moo[500] would be one byte per element right?
int moo[500] would be two or four bytes per element or whatever.
But is there an easy way to have an array of bits? So its 1 bit per element?
Name:
Anonymous2006-03-08 10:54
sizeof(type);
Name:
Anonymous2006-03-08 10:57
You can try use char and use '1' and '0' to represent bits. There is no 'bit' datatype, ie a datatype which represents directly bits, since the computer indexes the memory using bytes.
you could have something like char byte[8] = "11001100" to represent the numeral 204, and use byte[i] to access each byte. You would, of course, have to write functions to parse these strings into integers, and vice versa. String into integer is pretty easy to do, but the only way to 'extract' the bits from a byte in C is to use shift operations (>> and << binary operators), and you may not be familiar to them yet.
Name:
Anonymous2006-03-08 10:58
>>and use byte[i] to access each byte.
I mean bit. fixed.
Thanks, I'd forgetten about them 'til you mentioned it!
Name:
Anonymous2006-03-09 3:42
the only way to 'extract' the bits from a byte in C is to use shift operations (>> and << binary operators), and you may not be familiar to them yet.
bitwise operators.
To get the contents of 01001010[5] you would do
char c = (01001010 & ((char)(1<<5)))) >> 5
c will now be 0 if bit 5 is 0 and 1 if bit 5 is 1
Name:
Anonymous2006-03-09 4:05
That's a bit overkill though.
Another simpler way is to use a bitmask with a bitwise and. For all intents and purposes the result will serve the same function (ie: if you do an if(result){}).
Name:
Anonymous2006-03-09 4:23
>>10
Since any nonzero value is considered true, bitshifting is unnecessary.