整数到字节转换 [英] Integer to byte conversion

查看:524
本文介绍了整数到字节转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个整数,13941412,我想分成几个字节(数字实际上是一个颜色的形式0x00bbggrr)。你会怎么做的?在c中,你将数字转换为BYTE,然后移位。

Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?

推荐答案

使用按位数学运算符,字节已经存在:

Use bitwise mathematical operators, the "bytes" are already there:

def int_to_rgb(n):
    b = (n & 0xff0000) >> 16
    g = (n & 0x00ff00) >> 8
    r = (n & 0x0000ff)
    return (r, g, b)

这篇关于整数到字节转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆