casting int[] to bool[]

Derek Parnell derek at psych.ward
Wed Jan 28 23:41:19 PST 2009


On Thu, 29 Jan 2009 02:20:08 +0100, Saaa wrote:

>  int[] a = [1,2,3,0];
>  int[] aa = [0,1,0,1];
>  bool[] b = cast(bool[])a.dup;
>  bool[] bb = cast(bool[])aa.dup;
>  writefln(a,`-->`,b);
>  writefln(aa,`-->`,bb);

Casting is not always the same as converting. In this case you are NOT
converting an array of ints to an array of bools, instead you are telling
the compiler to pretend that the array of ints is really an array of bools.

> [1 2 3 0]-->[true false false false true false false false true false
> false false false false false false]
> [0 1 0 1]-->[false false false false true false false false false
>  false false false true false false false]

In each case you have sixteen bools because each of the four ints uses four
bytes and is thus is sixteen bytes long. Each byte is interpreted by
writefln() as a bool value. 

If you need to use 'ints' as bool values you have to provide your own
conversion routine. For example ...

  int[] a = [1,2,3,0];
  bool[] b;
  -- Convert to int array to bool array.
  b.length = a.length;
  foreach( i, x; a) 
     b[i] = (x != 0);

  writefln(a,`-->`,b);

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell


More information about the Digitalmars-d-learn mailing list