# python
实现 java
无符号右移, python
中只有右移 >>
和左移 <<
, 为了实现 java
的 >>>
!!!如非必要,不要使用 python
复现 java
,好多坑... 使用 js
复现 java
代码更方便些,当然直接调 jar
包更完美😁
- 另外 python 的左移存在一定的问题,当数据过大时,python 左移的结果和其他语言不一致,可以使用下面的代码解决
| |
| import ctypes |
| |
| |
| def int_overflow(val): |
| maxint = 2147483647 |
| if not -maxint-1 <= val <= maxint: |
| val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1 |
| return val |
| |
| |
| def unsigned_right_shift(n,i): |
| |
| if n<0: |
| n = ctypes.c_uint32(n).value |
| |
| if i<0: |
| return -int_overflow(n << abs(i)) |
| |
| return int_overflow(n >> i) |
| int_overflow(1701273967 << 3) |
| 1701273967 << 3 |
| |
| unsigned_right_shift(-160556357, 3) |
| def pb2jb(byte_arr): |
| """ |
| python字节码转java字节码 |
| :param byte_arr: |
| :return: |
| """ |
| return [int(i) - 256 if int(i) > 127 else int(i) for i in byte_arr] |
| |
| def jb2pb(byte_arr): |
| """ |
| java 字节码转python字节码 |
| :return: |
| """ |
| return [i + 256 if i < 0 else i for i in byte_arr] |
| |
| def hex2jb(hex_str): |
| """ |
| 十六进制数据转java字节码 |
| eg: |
| hex_str = "5f 3c f2 81 c8 0f 88 89 c7 b1 99 77 58 c5 4c 04" |
| :return: |
| """ |
| return [int(i, 16) - 256 if int(i, 16) > 127 else int(i, 16) for i in hex_str.split(" ")] |
| |
| def hex2pb(hex_str): |
| """ |
| 十六进制数据转python字节码 |
| eg: |
| hex_str = "5f 3c f2 81 c8 0f 88 89 c7 b1 99 77 58 c5 4c 04" |
| :return: |
| """ |
| return [int(i, 16) for i in hex_str.split(" ")] |
| |
| def pb2str(byte_arr, encoding="utf-8"): |
| """ |
| python字节码转str |
| :return: |
| """ |
| return bytes(byte_arr).decode(encoding) |
| |
| def jb2str(byte_arr, encoding="utf-8"): |
| """ |
| java字节码转str |
| :return: |
| """ |
| return bytes(jb2pb(byte_arr)).decode(encoding) |
| |
| def hex2str(hex_str, encoding="utf-8"): |
| """ |
| hex转str |
| :param hex_str: "2c 22 70 61 79 63 68 65 63 6b 6d 6f 64 65 22 3a" |
| :param encoding: |
| :return: |
| """ |
| return bytes(hex2pb(hex_str)).decode(encoding) |