Question

i have a uitableview, which gets populated by a pulling data from a website, so there is a new string for every cell. To that, i want to have show a HEX for the user, based on the text in the cell.

I have tryed myself to make it, without luck, but luckly found a javascript script which does what i try to do. This script, i now need to convert to obj-c, i have tryed it myself, but failed. I hope to get some help.

javascript: http://jsfiddle.net/sUK45/

My try in obj-c (here the strings aint based on the data from the web, but just an array):

unichar hash = 0;

        NSArray *strings = [NSArray arrayWithObjects:@"MA", @"Ty", @"Ad", @"ER", nil];

        for (int i = 0; i < [[strings objectAtIndex:indexPath.row] length]; i++) {
            hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);
        }

        NSString *colour = @"#";
        for (int i = 0; i < 3; i++) {
            int value = (hash >> (i * 8)) & 0xFF;
            colour = [NSString stringWithFormat:@"%@%d", colour, value];
        }

        NSLog(@"%@", colour);

But the data i get, aint a useable HEX - NSlog:

#2432550
#3600
#3400
#1200
Was it helpful?

Solution

Probably this is not the only one mistake. Change

hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);

to

hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash << 5) - hash);

UPDATE:

Also change

colour = [NSString stringWithFormat:@"%@%d", colour, value];

to

colour = [NSString stringWithFormat:@"%@%02x", colour, (unsigned int)value];

UPDATE2:

I have fixed one more error and simplified code:

unsigned int hash = 0;

NSArray *strings = [NSArray arrayWithObjects:@"MA", @"Ty", @"Ad", @"ER", nil];
NSString *string = [strings objectAtIndex:indexPath.row];

for (int i = 0; i < string.length; i++) {
    hash = [string characterAtIndex:i] + ((hash << 5) - hash);
}

NSString *color = [NSString stringWithFormat:@"#%06x", hash % 0x1000000];
NSLog(@"%@", color);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top