Thread overview | ||||||
---|---|---|---|---|---|---|
|
February 21, 2004 Bit Arrays and Other Types | ||||
---|---|---|---|---|
| ||||
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? |
February 21, 2004 Re: Bit Arrays and Other Types | ||||
---|---|---|---|---|
| ||||
Posted in reply to Owen | 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/ |
February 21, 2004 Re: Bit Arrays and Other Types | ||||
---|---|---|---|---|
| ||||
Posted in reply to Owen | "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]); |
February 21, 2004 Re: Bit Arrays and Other Types | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ben Hinkle | 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/ |
Copyright © 1999-2021 by the D Language Foundation