XOR a bunch of data

Koroskin Denis 2korden at gmail.com
Wed Jul 9 03:14:14 PDT 2008


On Wed, 09 Jul 2008 02:43:12 +0400, Dave Akers <dragon at dazoe.net> wrote:

> Charles wrote:
>>> Am I not allowed to XOR a bunch of data like this X[] ^= Y[] ???
>>> Thanks!
>>  Not yet, those are whats been dubbed 'array arithematic operations' ,  
>> and I
>> think are planned for 2.0 ( hopefully sooner , can't really call them
>> first-class arrays w/o em! ).
>>  It would probably look like : X ^= Y ;
>>  Thanks,
>> Charlie
>>
>
> Any idea how this will be implemented? something like
>
> ArrayXor(ubyte[] X, ubyte[] Y) {
> 	for (int i=0; i<X.length; i++) {
> 		X[i] ^= Y[i % Y.length];
> 	}
> }
>
>
>>  "Tiago Gasiba" <tiago.gasiba at gmail.com> wrote in message
>> news:dj0e3m$cku$1 at digitaldaemon.com...
>>> Hi all,
>>>
>>>   Why can't I do the following?
>>>
>>> --- code ---
>>> import std.c.stdio;
>>> import std.c.stdlib;
>>>
>>> int main( ){
>>>   ulong[10] X, Y;
>>>   X[] = 2;
>>>   Y[] = 5;
>>>   X[] ^= Y[];
>>>
>>>   foreach( ulong u; X )
>>>     printf("%lu\n",u);
>>>
>>>   return 0;
>>> }
>>> --- code ---
>>>
>>> The compiler complains:
>>> test.d(8): slice expression X[] is not a modifiable lvalue
>>> test.d(8): 'X[]' is not a scalar, it is a ulong[]
>>> test.d(8): 'X[]' is not of integral type, it is a ulong[]
>>> test.d(8): 'Y[]' is not of integral type, it is a ulong[]
>>>
>>> What I want to do is simply this:
>>>
>>>   for( int ii=0; ii<X.length; ii++ )
>>>     X[ii] ^= Y[ii];
>>>
>
> what if Y.length < X.length... array bounds error...
>
>
>>> Am I not allowed to XOR a bunch of data like this X[] ^= Y[] ???
>>> Thanks!
>>>
>>> Best,
>>> Tiago Gasiba
>>> --
>>> Tiago Gasiba (MSc.) - http://www.gasiba.de
>>> Everything should be made as simple as possible, but not simpler.
>>

An exception will be thrown, I think:
BTW, operation may be done faster if 4 bytes is xored per step (or even  
8-bytes per step on x64):
int* dst = cast(int*)X.ptr;
int* src = cast(int*)Y.ptr;

// xor
int steps = X.length / X[0].sizeof;
for (int i = steps; i >= 0; --i, ++src, ++dst) {
    *dst ^= *src;
}
// xor remaining byte-per-byte, code skipped.


More information about the Digitalmars-d-learn mailing list