1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで16進数文字列を符号付き整数に変換する

Last updated at Posted at 2021-02-02

Pythonで16進数文字列を符号付き整数に変換する

組込み関数で符号なし整数に変換し、指定したビット数の最後のビットで符号を判断しています。

コード

※ python初心者のため、例外処理がわかりません。あしからず。

# エラー用
class ExceededMaxValue(Exception):
    pass

## 16進数文字列を指定したビットの範囲で符号付き整数に変換する
def Hex2Dec(x:str,bit):
    dec = int(x, 16)
    
    # 指定したビットの範囲より大きい16進数文字列が入った場合に
    # エラーとする
    if dec >= (1 << bit):
        raise ExceededMaxValue
        # or
        # return 0
    
    # 指定したビット以上の値を捨てる
    dec = dec & ((1 << bit) -1)
    
    ## 指定したビットの範囲でマイナスかどうか
    if dec & (1 << (bit-1)) != 0:
        return ((1 << bit) - dec) * -1
    else:
        return dec 

簡略化したコード ※追記(2021/02/03)

コメントで@shiracamus 様から、上記のコードを簡略化してくださいました。
とてもすっきりして使いやすいです! 普段使用する際は、こちらのコードをぜひ!

def hex2dec(x: str, bit: int) -> str:
    """16進数文字列xをビット数bit内の符号付き整数に変換する"""
    dec = int(x, 16)
    if dec >> bit:
        raise ValueError
    return dec - (dec >> (bit - 1) << bit)


print(hex2dec("00", 8))
print(hex2dec("7f", 8))
print(hex2dec("80", 8))
print(hex2dec("ff", 8))
print(hex2dec("100", 8))
実行結果
0
127
-128
-1
Traceback (most recent call last):
  File "hex2dec.py", line 13, in <module>
    print(hex2dec("100", 8))
  File "hex2dec.py", line 5, in hex2dec
    raise ValueError
ValueError

追記(2022/03/28)

@fujitanozomu

編集リクエストを受信していたことに今気づきました、、、 遅くなってしまいすみませんでした。。。

1
2
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?