Python: convert int to mode string

 

复制代码
def _convert_mode(mode: int):
    if not 0 <= mode <= 0o777:
        raise RuntimeError
    res = ''

    for v in range(0, 9):
        if mode >> v & 1:
            match v % 3:
                case 0:
                    res = 'x' + res
                case 1:
                    res = 'w' + res
                case 2:
                    res = 'r' + res
        else:
            res = '-' + res
    return res


print(_convert_mode(0o757))

mode_list = dict(zip(range(9), list('rwx') * 3))


def _convert_mode(mode: int):
    if not 0 <= mode <= 0o777:
        raise ValueError

    res = ''
    # 8 -> 0, 7 -> 1  =>  v + x = 8
    for v in range(8, -1, -1):
        if mode >> v & 1:
            res += mode_list[8 - v]
        else:
            res += '-'
    return res


print(_convert_mode(0o577))
复制代码

 

posted @   ascertain  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-11-10 Solve Disk Space Occupancy Rate in Linux & Clear Docker logs
点击右上角即可分享
微信分享提示