www.digitalmars.com         C & C++   DMDScript  

D - Bit Arrays and Other Types

reply Owen <Owen_member pathlink.com> writes:
If I have an array of 32 bits, can I cast this to an integer?  Or do I need to
declare a union of this array 
with an integer an then access the array as an integer through that?
Feb 20 2004
next sibling parent J Anderson <REMOVEanderson badmama.com.au> writes:
Owen wrote:

If I have an array of 32 bits, can I cast this to an integer?  Or do I need to
declare a union of this array 
with an integer an then access the array as an integer through that?

  
You'll have to use a union (although I would argue for a cast version). It's pretty doggie code (well at least my version is). union bittoarray { bit [] BIT; int [] INT; } int [] convert(bit [] array) { bittoarray cov; cov.BIT = array; cov.INT.length = cov.INT.length / (int.sizeof * 8); return cov.INT; //Note that you should no longer use the bit version } int main ( char [] [] args ) { bit [] barray; barray.length = 32; barray[2] = 1; int [] iarray = convert(barray); printf("%d\n", iarray.length); printf("%d\n", iarray[0]); } -- -Anderson: http://badmama.com.au/~anderson/
Feb 21 2004
prev sibling parent reply "Ben Hinkle" <bhinkle4 juno.com> writes:
"Owen" <Owen_member pathlink.com> wrote in message
news:c16l96$25bg$1 digitaldaemon.com...
| If I have an array of 32 bits, can I cast this to an integer?  Or do I need to
| declare a union of this array
| with an integer an then access the array as an integer through that?

How about
   bit[] p1;
   int[] p2;
   p1 = new bit[32];
   p1[0] = 1;
   p1[2] = 1;
   p2 = (cast(int*)p1)[0..1];
   printf("%d\n",p2[0]);
   p2[0] = 4;
   printf("%d %d\n",p1[0],p1[2]);
Feb 21 2004
parent J Anderson <REMOVEanderson badmama.com.au> writes:
Ben Hinkle wrote:

"Owen" <Owen_member pathlink.com> wrote in message
news:c16l96$25bg$1 digitaldaemon.com...
| If I have an array of 32 bits, can I cast this to an integer?  Or do I need to
| declare a union of this array
| with an integer an then access the array as an integer through that?

How about
   bit[] p1;
   int[] p2;
   p1 = new bit[32];
   p1[0] = 1;
   p1[2] = 1;
   p2 = (cast(int*)p1)[0..1];
   printf("%d\n",p2[0]);
   p2[0] = 4;
   printf("%d %d\n",p1[0],p1[2]);
  
I stand corrected. -- -Anderson: http://badmama.com.au/~anderson/
Feb 21 2004