Path: utzoo!attcan!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: Overloading [] to read and write to a bit array Keywords: bit, array, c++, [] Message-ID: <55655@microsoft.UUCP> Date: 5 Jul 90 16:34:53 GMT References: <13053@shlump.nac.dec.com> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 79 In article <13053@shlump.nac.dec.com> heintze.peewee.enet.dec.com (Sieg Heintze) writes: >Actually, what I really want is to access my VGA video memory with the [] >operater. This would actually be a two dimensional array of 4 bit entities >(nibbles). Currrently, we have to do some pretty low level stuff everytime we >have to access this video memory. If C++ truly is OOP, we should be able to >hide these ugly idiosynchrousies (sp?) inside the [] operator. Below find an example of one [slightly hack] way to use operator[] on nibbles. I assume you can take the below example of using a generalized reference class and expand it to handle 2d arrays. extern "C" { #include "stdio.h" } // the following example of nibble arrays assumes pointers are 32-bit quantities// -- far or flat model pointers, for example, and that the high order bit of // the pointers aren't actually being used [ true on most computers ] // if your talking nibbles to external hardware, beware packing order -- the // below has a 50/50 chance of not being the order you want [but that's easy to // fix] class NIBLREF { public: unsigned long nibladdr; NIBLREF(const NIBLREF& n) : nibladdr(n.nibladdr) {} NIBLREF(unsigned long n) : nibladdr(n) {} // i assumed to be a valid nibble without checking NIBLREF& operator=(const int i) { unsigned char& c = *(unsigned char*)(nibladdr>>1); if (nibladdr & 1) { c &= 0x0F; c |= i << 4; } else { c &= 0xF0; c |= i; } return *this; } operator int() { unsigned char& c = *(unsigned char*)(nibladdr>>1); return (nibladdr & 1) ? (c >> 4) : (c & 0x0F); } }; class NIBLARY { public: const unsigned char* p; NIBLARY(int i) : p(new unsigned char[i]) {} ~NIBLARY() { delete (void*)p; } NIBLREF operator[](int i) { return (((unsigned long)p)<<1) + i; } }; main() { NIBLARY n1(100); NIBLARY n2(100); int i; for (i=0; i<100; ++i) n1[i] = i % 10; for (i=0; i<100; ++i) n2[i] = n1[i]; for (i=0; i<100; ++i) printf("%d\n", (int)n2[i]); }