segunda-feira, março 26, 2007

My god!! I just smoked the peace pipe with pointers!!

Few things in life (right now lol) bring me more pleasure then saving a line of code, or a variable. And a pointer does just that! Because it's a variable and an iterator all in one! ;) Well sort of, you can use it both ways.

As an iterator, because it's really a memory index so... if you increase it you go to the next memory index, same if you decrease it , or add a given quantity to it etc. (search for pointer arithmetic) Great to arrays!!

And as a variable, because using the operator * you can access whatever the pointer points to.


Anyway, the hole reason for my excitement is not in pointers. It's I've been looking arround for a magical function that would transform an integer to a char array,but I couldn't find the code!! So I made one :P After stretching my brain a while I came up with this.

char * itc(char *d, int n){ /*int to char binary*/
    char *init;
    int i;
    init = d;
     for(i=sizeof(int)*8 -1; i>=0; i-- , d++ )
       *d= ((n>>i)&1 ) + '0';

    *d='\0';
    return init;
}


itc receives a pointer to a char array (one assumes big enough!! Easy peasy say you declare it like : char myLovelyCharArray[sizeof(int)*8]; Remenber: 1 byte == 8 bits) :P

We need to return the beginning of the string so we save it in init.

Then the brilliant Idea is to go bit by bit. But, but ohh my god! How am I gonna do that? int is bytes in memory but how am I going to access that? [that was my reaction when it stroke me anyway]. So then I reminded the bitwise operator. But never really got how to use it and Ritchie wasn't much of a help because the example was way to complicated for strike one :P so I experimented a little till I finally got it.

Do you have your boolean algebra up to date?
say 6 => 011 0
now shift right is an interesting concept if one considers it this way : what's the value of bit in position 1 ? Meaning if I divide 6 by 2^1 what do I get? 2=11 = 0011 .
Here's a visual example:

shift    (0110)>>nBits)&1

0110>>0 => 0
0110>>1 => 1
0110>>2 => 1
0110>>3 => 0

So our task becomes as simple as to translate this int value in to correspondent char. So we take advantage of the ASCII code ;) and just add the shift to it. If zero then = '0' otherwise = '0' +1; meaning 48 or 49. (6) ohh lovely. :P