From bf5433b7c580d87a4cac32e3b7510dc8eb154388 Mon Sep 17 00:00:00 2001 From: Andy Fingerhut Date: Sat, 24 Jun 2023 12:00:32 -0400 Subject: [PATCH] Support negative-valued action parameters (#483) by converting them in the Python helper code into a positive value whose bit pattern is the 2's complement representation of the negative value. --- utils/p4runtime_lib/convert.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/utils/p4runtime_lib/convert.py b/utils/p4runtime_lib/convert.py index 671b910..9bb372e 100644 --- a/utils/p4runtime_lib/convert.py +++ b/utils/p4runtime_lib/convert.py @@ -48,7 +48,17 @@ def bitwidthToBytes(bitwidth): def encodeNum(number, bitwidth): byte_len = bitwidthToBytes(bitwidth) + # If number is negative, calculate the positive number that its + # 2's complement encoding would look like in 'bitwidth' bits. + orig_number = number + if number < 0: + if number < -(2 ** (bitwidth-1)): + raise Exception("Negative number, %d, has 2's complement representation that does not fit in %d bits" % (number, bitwidth)) + number = (2 ** bitwidth) + number num_str = '%x' % number + if orig_number < 0: + print("CONVERT_NEGATIVE_NUMBER debug: orig_number=%s number=%s bitwidth=%d num_str='%s'" + "" % (orig_number, number, bitwidth, num_str)) if number >= 2 ** bitwidth: raise Exception("Number, %d, does not fit in %d bits" % (number, bitwidth)) return bytes.fromhex('0' * (byte_len * 2 - len(num_str)) + num_str)