Python中EBCDIC(CP037)编码转大型机时部分值异常求助
问题:COMP-3转EBCDIC(CP037)时部分值转换异常
我用Python实现EBCDIC(CP037)编码并向大型机发送文件,多数场景运行正常,但部分值转换结果异常。例如:
- 十六进制值43被转为BC、56被转为DA;
- 输入340312时结果正确,但输入343012时得到错误的3BC012。
以下是相关转换函数:
COMP-3转换函数
def unsigned_comp3(decimal_num, bytecount): sign_nibble = "1111" # F for positive numbers # Convert the decimal number to a string of BCD digits bcd_str = ''.join([f"{int(d):04b}" for d in str(decimal_num)]) bcd_len = len(bcd_str) # Add a leading nibble of "1111" to indicate that the number is packed in COMP-3 format bcd_str = bcd_str + sign_nibble print(f'bcd{decimal_num}: {bcd_str}') # Group the BCD digits into pairs of bytes byte_pairs = [bcd_str[i:i + 8] for i in range(0, len(bcd_str),8)] print(f'bytes{decimal_num}: {byte_pairs}') # Convert each byte pair to its hexadecimal equivalent hex_str = ''.join([f"{int(pair, 2):02X}" for pair in byte_pairs]) # To EBCDIC output_str = to_ebcdic(hex_str, len(str(decimal_num)), bytecount) # Return hex string return output_str
EBCDIC转换函数
def to_ebcdic(input_str, input_length, bytecount): # Store the last character sign_char = input_str[-1] # Concatenate the remaining character and the sign character if sign_char == "D": # Remove the first character stripped_str = input_str[1:] input_hex = stripped_str[:input_length - 1] + sign_char elif sign_char == "F": input_hex = input_str[:input_length] + sign_char else: # Remove the first character stripped_str = input_str[1:] input_hex = stripped_str[:input_length] + sign_char # Padding if input_str is less than bytecount pad_str = pad_string(input_hex, bytecount) print(f'{pad_str}') # Convert the hex string to bytes input_bytes = bytearray.fromhex(pad_str) print(f'input bytes{input_str}: {input_bytes}') # Decode the bytes using EBCDIC encoding ebcdic_str = input_bytes.decode('cp037') print(f'ebcdic string{input_str}: {ebcdic_str}') # Return the decoded string return ebcdic_str
异常示例
大型机侧显示输入343012F时转换结果错误。
内容的提问来源于stack exchange,提问作者amandeep gandhi
相关产品推荐
相关产品推荐

