简体   繁体   English

PYthon:该代码如何工作?

[英]PYthon: How does this code work?

def color(self):
    name_hash = hash(self.name)

    red = name_hash & 0xFF          # What is this sort of operation? 
    green = (name_hash << 0xFF) & 0xFF            # What does 0xFF used for?
    blue = (name_hash << 0xFFFF) & 0xFF

    make_light_color = lambda x: x / 3 + 0xAA     # Why plux 0xAA?

    red = make_light_color(red)
    green = make_light_color(green)
    blue = make_light_color(blue)

    return 'rgb(%s,%s,%s)' % (red, green, blue)

This code is trying to convert a hash value to a color; 这段代码试图将哈希值转换为颜色。 parts of the computation are buggy. 计算的一部分是越野车。 It takes the lowest 24 bits of name_hash , splits them into 3 bytes, makes those colors lighter, and then outputs that as a string. 它使用name_hash的最低24位,将它们分成3个字节,使这些颜色变浅,然后将其输出为字符串。 Going through the sections: 浏览各节:

red = name_hash & 0xFF

Gets the least significant 8 bits of name_hash (the & operation is bitwise AND, and 0xFF selects the lowest 8 bits). 获取name_hash的最低有效8位( &操作按位与, 0xFF选择最低的8位)。 The lines for green and blue are buggy; greenblue的线是马车。 they should be: 他们应该是:

green = (name_hash >> 8) & 0xFF
blue = (name_hash >> 16) & 0xFF

to get the middle and high blocks of 8 bits each from name_hash . name_hash获得8位的中高块。 The make_light_color function does what the name says: it changes a color value from 0 to 255 into one from 170 to 255 (170 is 2/3 of the way from 0 to 255) to make it represent a lighter color. make_light_color函数的作用与名称相同:它将颜色值从0更改为255,将颜色值更改为170至255(170是0到255的2/3),以使其代表较浅的颜色。 Finally, the last line converts the values of the three separate variables into a string. 最后,最后一行将三个独立变量的值转换为字符串。

Where did you find this code? 您在哪里找到此代码?

  • & is the binary AND operation, ANDing with 0xFF would result in all the bits in your character which are 1 for the 2 byte word. &是二进制AND运算,与0xFF AND运算会导致您字符中的所有位(对于2字节字而言)均为1。

  • << is the left shift operation, which would move the bits towards left and append 0's to the right. <<是左移操作,它将向左移动位,并向右追加0。

  • The 0xAA seems to be some operation to perform a color transition, that is modify the bit values to make the color light. 0xAA似乎是执行颜色转换的某种操作,即修改位值以使颜色变浅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM