简体   繁体   English

Python中的十六进制转换错误

[英]Hexadecimal conversion error in Python

I have a problem. 我有个问题。

I have a page where I send commands to a sensor network. 我有一个页面,可以在其中发送命令到传感器网络。

When I click on this part of code 当我点击这部分代码时

<a href='javascript:void(send_command_to_network("{{net.id}}", "restartnwk"));'>Restart Network <i class="icon-repeat"></i> </a>

I call a js function, this: 我称这为js函数:

function send_command_to_network(net, command) {
    $.ajax({url: "/networks/" + net + "/send?command=" + command,
    type: "GET",
    async: true,
    dataType: "json",
    success: function(json_response) { 
         var err = json_response['error'];
     if (err) {
       show_alert('error', err);
       return;
     }
     var success = json_response['success'];
     if (success) {
       show_alert('success', success);
       return;
     }
     show_alert('alert', "This should not happen!");
       }
     }); 
    }

This function build a url that recall an handler in the Tornado web server written in python. 此函数将建立一个URL,该URL可以调用以Python编写的Tornado Web服务器中的处理程序。 The handler is this: 处理程序是这样的:

class NetworkSendHandler(BaseHandler):
    # Requires authentication 
    @tornado.web.authenticated
    def get(self, nid):
        # Get the command 
        command = self.get_argument('command').upper(); 

        # The dictionary to return
        ret = {}

        #Check if the command is available
        if command not in ['RESTARTNWK']:
            raise tornado.web.HTTPError(404, "Unknown command: " + str(command))


        #Command ZDP-RestartNwk.Request
        if command == 'RESTARTNWK':
            op_group = "A3"
            op_code = "E0"
            packet_meta = "*%s;%s;%s;#"
            pkt_len = hextransform(16, 2)

            packet = packet_meta % (op_group, op_code, pkt_len)
            packet = packet.upper()

            op_group_hex=0xA3
            op_code_hex=0xE0

            cmdjson = packet2json(op_group_hex,op_code_hex, packet)

        self.finish()

I receive this error in the Tornado debug consolle: 我在Tornado调试控制台中收到此错误:

Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 1739, in wrapper
    return method(self, *args, **kwargs)
  File "./wsn.py", line 859, in get
    cmdjson = packet2json(op_group_hex,op_code_hex, packet)
  File "./wsn.py", line 188, in packet2json
    fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)
ValueError: invalid literal for int() with base 16: '0x*A'

I think the error is after the calling of packet2json. 我认为错误是在packet2json调用之后。 And I think the error is in a conversion inside the function, because the error says that '0x*A' isn't a valid int. 而且我认为错误在于函数内部的转换中,因为错误表明“ 0x * A”不是有效的int。 I think the '*' is the error.... How can I resolve this? 我认为“ *”是错误。...我该如何解决?

EDIT 编辑

Sorry, I forgot the functions: 抱歉,我忘记了以下功能:

# Transform an integer into a string with HEX symbols in the format that is
# understandable by Quantaservd
def hextransform(data, length):
    data = hex(data).lstrip('0x').rstrip('L')
    assert(len(data) <= length)
    # zero-padding
    data = ('0' * (length - len(data))) + data
    print data
    # Swap 'bytes' in the network ID
    data = list(data)
    for i in range(0, length, 2):
        tmp = data[i]
        data[i] = data[i + 1]
        data[i + 1] = tmp
    # Reverse the whole string (TODO: CHECK) 
    data.reverse()
    data = "".join(data)
    return data


def packet2json(op_group, op_code, payload): 
    #op_group =
    #op_code =
    #payload=""    # stringa ascii 2 char per byte, senza checksum 
    lun = len(payload) / 2
    fcs = op_group ^ op_code ^ lun #fcs = XOR of op_groip, op_code, lenght and  payload
    for i in range(len(payload)):
    if ((i % 2) == 1):
        fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)
        print int('0x' + payload[(i - 1):(i + 1)], 16)
    s=cmd_payload(op_group,op_code, lun, payload, fcs)
    #p = r '{"data": "' + s + r '"}'
    p=r'{"data": "'+s+r'"}'
    return p

the problem lies in the packet2json() function: 问题出在packet2json()函数中:

for i in range(len(payload)):
    if ((i % 2) == 1):
        fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)

in your program, you call this function like this: 在程序中,您可以这样调用此函数:

packet2json(0xa3, 0xe0, '*A3;E0;10;#')

now the loop above will start with the first character (index 0), ignore it because its index is not odd, then go to the second character (index 1) whose index is odd (1%2 == 1). 现在,上面的循环将从第一个字符(索引0)开始,由于其索引不为奇数而忽略它,然后转到索引为奇数(1%2 == 1)的第二个字符(索引1)。 the body of the if statement, uses int('0x' + payload[(i-1):(i+1)], 16) , that is int('0x' + payload[0:2], 16) , that is int('0x*A',16) , which will always crash... if语句的主体使用int('0x' + payload[(i-1):(i+1)], 16) ,即int('0x' + payload[0:2], 16) ,那是int('0x*A',16) ,它将始终崩溃...

you shall rewrite this packet2json() function to use the correct string indices, or call it correctly without the leading * in the payload. 您应重写此packet2json()函数以使用正确的字符串索引,或在有效载荷中不带前导*情况下正确调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM