Numeric access to char[]
Regan Heath
regan at netwin.co.nz
Wed Aug 23 19:21:49 PDT 2006
On Thu, 24 Aug 2006 03:53:28 +0200, Peter Thomassen
<info at peter-thomassen.de> wrote:
> Regan Heath schrieb am Mittwoch, 23. August 2006 02:06:
>> Depends what exactly you're trying to do, perhaps this:
>>
>> import std.stdio;
>>
>> void main()
>> {
>> char[] c = "azAZ";
>> int val;
>> val = (cast(int*)c.ptr)[0..1][0];
>> //DEBUG
>> //writef("(%02d)%08b",c[0],c[0]);
>> //writef(",(%02d)%08b",c[1],c[1]);
>> //writef(",(%02d)%08b",c[2],c[2]);
>> //writefln(",(%02d)%08b",c[3],c[3]);
>> writefln("%032b",val);
>> val >>= 1;
>> writefln("%032b",val);
>> }
>
> Thanks, this is what im looking for! But I don't understand this line:
>> val = (cast(int*)c.ptr)[0..1][0];
>
> What does [0..1][0] mean?
Ahh.. to understand the line we need to know that D allows us to slice
pointers and the result is an array, lets break the line into steps.
Step1: cast(int*)c.ptr, this tells it to pretend the pointer to the char[]
data is an int pointer.
Step2: [0..1], this requests a slice (AKA array) of the data referenced by
the (now) int pointer. The result is an int[], in this case with only 1
item, a single int.
Step3: [0] returns the first item (only item) in the int slice (array), an
int.
Because we're only after a single int, we can actually do it in a much
simpler fashion, this:
val = *(cast(int*)c.ptr);
If you have a large block of char[] data to process you might use:
char[] c = "the quick brown fox jumps over the lazy dog";
foreach(int val; cast(int[])c)
{
..etc..
}
or similar.
>> p.s. nobody got the ascii values backward ('A' is 65, 'a' is 97)
>> it's nobody's fault really.. nobody is to blame..
>>
>> "nobody" I love the nick.. have you read the "Deverry" novels by
>> "Katherine Kerr"?
>> http://www.math.ttu.edu/~kesinger/deverry/kerr.biblio.html
>
> The oldest example of such pun I know of is Polyphemus who is fooled by
> this
> name in Homer's Odyssey which I read parts of in my Latin lessons at
> school
> (albeit the original is Greek). -->
> http://en.wikipedia.org/wiki/Polyphemus
Cool.
Regan
More information about the Digitalmars-d-learn
mailing list