Python/Basic
blockchain 테스트에 사용한 python 함수 - convertToHex
Tongchun
2018. 12. 17. 18:20
blockchain 테스트에 사용한 python 함수를 설명합니다.
- getDateStrings - 날짜 - 년, 월, 일, 시, 분, 초를 확인하는 함수입니다.
- getLogfileNameWithPath - 로그 기록을 위해 폴더를 생성하고 경로를 반환합니다.
- getRequestId - ramdom으로 숫자를 반환합니다.
- moveFile - 특정 파일을 로그 폴더로 이동시킵니다.
- saveResultData - 데이터를 파일에 저장합니다.
- convertToHex - String을 hex로 변환합니다.
- leftPad64 - 왼쪽에 (또는 오른쪽에) 0을 채워 고정된 길이로 만듭니다.
- getTestConfig - json 형태의 config 파일을 만들고 불러옵니다.
- waitingCount - time.sleep() 할 때 동적으로 카운트를 셉니다.
- callRPC - requests 모듈을 사용해 http API를 호출합니다.
- callWS - websocket 모듈을 사용해 API 통신을 합니다.
Blockchain쪽은 대부분의 데이터를 hex로 변경해 사용했습니다.
테스트를 위해 string이나 int를 hex 데이터로 변경하고 또 hex 데이터를 string이나 int로 변환해야 했습니다.
int의 hex변환이나 그 반대의 경우 간단하게 hex() 함수나 int() 함수를 사용하면 됩니다.
hex(1026) # '0x402' int(0x402) # 1026 int('0x402', 16) # 1026
string 데이터를 hex로 만들어야 했는데 간단하게 함수를 만들어 사용했습니다.
# coding=utf-8 import codecs class nGleUtils(): def convertToHex(self, message): '''string, int 데이터를 hex 데이터로 변환합니다.''' hexData = "" # message가 string 타입일 경우 if isinstance(message, str): hexData = "0x" + "".join("{:02x}".format(ord(c)) for c in str(message)) # message가 int 타입일 경우 if isinstance(message, int): hexData = hex(message) return hexData def convertHexToString(self, hexData): '''hex 데이터를 String으로 변환합니다.''' # hex 데이터의 0x를 제거합니다. if hexData[:2] == "0x": hexData = hexData[2:] stringData = codecs.decode(hexData, "hex").decode('utf-8', 'ignore') # replace null character stringData = stringData.replace("\x00", "") stringData = stringData.replace("\x16", "") return stringData if __name__== "__main__": ngle = nGleUtils() # Hi nGle!을 hex 데이터로 변경합니다. hexData = ngle.convertToHex('Hi nGle!') print(hexData) # hex 데이터를 string 데이터로 변경합니다. stringData = ngle.convertHexToString(hexData) print(stringData)
스크립트를 실행하면 아래와 같습니다.
$ python convertToHex.py 0x4869206e476c6521 Hi nGle!
String을 hex로 변경하는 코드는 아래와 같습니다.
hexData = "0x" + "".join("{:02x}".format(ord(c)) for c in str(message))
input으로 받은 message (String) 데이터를 for문을 사용해 character 한자 한자 불러옵니다.
불러온 character를 ord() 함수를 사용해 Unicode로 변환합니다. Unicode로 변환된 message 데이터를 {:02x}".format()을 사용해 hex 데이터로 변환합니다. 그리고 join을 사용해 앞에 0x를 붙여 줍니다.
hex 데이터를 String으로 변환하는 코드는 아래와 같습니다.
stringData = codecs.decode(hexData, "hex").decode('utf-8', 'ignore')
간단하게 codecs 모듈을 사용해 줍니다.