2

How can I define a very long hex literal over several lines in Python? E.g.

p = 0xB10B8F96 A080E01D DE92DE5E AE5D54EC 52C99FBC FB06A3C6
      9A6A9DCA 52D23B61 6073E286 75A23D18 9838EF1E 2EE652C0
      13ECB4AE A9061123 24975C3C D49B83BF ACCBDD7D 90C4BD70
      98488E9C 219A7372 4EFFD6FA E5644738 FAA31A4F F55BCCC0
      A151AF5F 0DC8B4BD 45BF37DF 365C1A65 E68CFDA7 6D4DA708
      DF1FB2BC 2E4A4371

It would be nice if I can keep the spaces or another separator like _ too.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Chin
  • 19,717
  • 37
  • 107
  • 164
  • 1
    Reading answers to http://stackoverflow.com/questions/12385040/python-defining-an-integer-variable-over-multiple-lines AND http://stackoverflow.com/questions/21879454/how-to-convert-a-hex-string-to-hex-number will give you the answer. – Yavar Dec 08 '15 at 06:23

2 Answers2

1

Here is one attempt, which saves it as a string, and then uses ast.literal_eval to calculate the actual number:

from ast import literal_eval

hex_string_literal = (
     "0xB10B8F96" "A080E01D" "DE92DE5E" "AE5D54EC" "52C99FBC" "FB06A3C6"
       "9A6A9DCA" "52D23B61" "6073E286" "75A23D18" "9838EF1E" "2EE652C0"
       "13ECB4AE" "A9061123" "24975C3C" "D49B83BF" "ACCBDD7D" "90C4BD70"
       "98488E9C" "219A7372" "4EFFD6FA" "E5644738" "FAA31A4F" "F55BCCC0"
       "A151AF5F" "0DC8B4BD" "45BF37DF" "365C1A65" "E68CFDA7" "6D4DA708"
       "DF1FB2BC" "2E4A4371")

p = literal_eval(hex_string_literal)

Defining the string literal above uses the string literal concatenation.

EDIT

As said by @nneonneo in comments below, you could also use int(hex_string_literal, 16) or int(hex_string_literal, 0) in example above, so that you don't have to import something extra.

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
1
p = int(''.join('''
    B10B8F96 A080E01D DE92DE5E AE5D54EC 52C99FBC FB06A3C6
    9A6A9DCA 52D23B61 6073E286 75A23D18 9838EF1E 2EE652C0
    13ECB4AE A9061123 24975C3C D49B83BF ACCBDD7D 90C4BD70
    98488E9C 219A7372 4EFFD6FA E5644738 FAA31A4F F55BCCC0
    A151AF5F 0DC8B4BD 45BF37DF 365C1A65 E68CFDA7 6D4DA708
    DF1FB2BC 2E4A4371
    '''.split()), 16)

You can use int(str, 16) to translate hex.

eph
  • 1,988
  • 12
  • 25