我有一个函数(不是我自己的),它需要0x*格式的十六进制值作为 colored颜色 值.我拥有的函数接受RGB值并将其转换为十六进制,但将其作为字符串输出.有没有办法将该字符串作为十六进制值进行计算?

我已经try 将十六进制值更改为整数,但该函数似乎不接受整数.

这是我拥有的函数,它获取RGB值并将其转换为十六进制.

def decToHexa(n): 
 
    # char array to store hexadecimal number 
    hexaDeciNum = ['0'] * 100
 
    # Counter for hexadecimal number array 
    i = 0
     
    while (n != 0): 
 
        # Temporary variable to store remainder 
        temp = 0
 
        # Storing remainder in temp variable. 
        temp = n % 16
 
        # Check if temp < 10 
        if (temp < 10): 
            hexaDeciNum[i] = chr(temp + 48)
            i = i + 1
 
        else: 
            hexaDeciNum[i] = chr(temp + 55)
            i = i + 1
 
        n = int(n / 16)
 
    hexCode = ""
    if (i == 2):
        hexCode = hexCode + hexaDeciNum[0] 
        hexCode = hexCode + hexaDeciNum[1] 
 
    elif (i == 1): 
        hexCode = "0"
        hexCode = hexCode + hexaDeciNum[0]
 
    elif (i == 0):
        hexCode = "00"
 
    # Return the equivalent 
    # hexadecimal color code 
    return hexCode
 
# Function to convert the 
# RGB code to Hex color code 
def convertRGBtoHex(R, G, B): 
 
    if ((R >= 0 and R <= 255) and
        (G >= 0 and G <= 255) and
        (B >= 0 and B <= 255)): 
 
        hexCode = "0x"; 
        hexCode = hexCode + decToHexa(R)
        hexCode = hexCode + decToHexa(G) 
        hexCode = hexCode + decToHexa(B) 
        return hexCode
 
    # The hex color code doesn't exist 
    else:
        return "-1"

下面是使用该值的位置:

def appendCharacter(self,ch,x,y,r,g,b):
        idx = self.numChars
        M = self.metrics[ch]
        self.textData[idx].screenXY = (x << 16) | y
        self.textData[idx].atlasXY = (M["x"]<<16) | M["y"]
        self.textData[idx].ascentDescentWidthLeftBearing = (
                (M["ascent"]<<24)   |
                (M["descent"]<<16)  |
                (M["width"]<<8)     |
                (M["leftbearing"]+128)      #make positive
        )
        self.textData[idx].color = int(convertRGBtoHex(r, g, b).lower(), 0)
        self.numChars+=1

我希望我能提供更多的信息,但我拥有的大部分代码都是由我的教授提供的,所以我对它们是如何协同工作的知之甚少.

推荐答案

您可以将整个decToHexa函数替换为

#08x = (0) pad (8) positions he(x)adecimal
hxd = f'0x{n:08x}'

转换回int的步骤

#convert to int using base 16
i = int(hxd, 16)

需要注意的是:似乎你认为它必须是十六进制格式才能使用移位.您可以对任何整数进行位移位.十六进制格式只是一种方便表示数字概念的方法.这是你正在移位的实际数字,而不是概念上的表示.换句话说,你根本不需要把它转换成十六进制,除非你正在使用的东西需要这种格式(即.一般为RGBA值).

Python相关问答推荐

Django关于UniqueBindition的更新

仅使用2种 colored颜色 创建热图

保留包含pandas pandras中文本的列

获取Azure Pipelines以从pyproject.toml(而不是relevments_dev.文本)安装测试环境

从Python调用GMP C函数时的分段错误和内存泄漏

Polars Select 多个元素产品

如何在Python中增量更新DF

pyramid 内部数组中的连续序列-两极

覆盖Django rest响应,仅返回PK

Python plt.text中重叠,包adjust_text不起作用,如何修复?

在Mac上安装ipython

我如何根据前一个连续数字改变一串数字?

ThreadPoolExecutor和单个线程的超时

海上重叠直方图

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

如何启动下载并在不击中磁盘的情况下呈现响应?

Python中的变量每次增加超过1

基于形状而非距离的两个numpy数组相似性

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame

用SymPy在Python中求解指数函数