Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - Print an integer array as hexadecimal numbers

I have an array created by using

array1 = np.array([[25,  160,   154, 233],
                   [61, 244,  198,  248],
                   [227, 226, 141, 72 ],
                   [190, 43,  42, 8]],np.int) ;

which displays as

[[25,  160, 154, 233]
 [61,  244, 198, 248]
 [227, 226, 141,  72]
 [190,  43,  42 ,  8]]

How do I display this array as hexadecimal numbers like this:

[[0x04,  0xe0,  0x48, 0x28]
 [0x66,  0xcb,  0xf8, 0x06]
 [0x81,  0x19,  0xd3, 0x26]
 [0xe5,  0x9a,  0x7a, 0x4c]]

Note: numbers in hex may not be real conversions of numbers in int. I have filled hex array just to give example of what I need.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set the print options for numpy to do this.

import numpy as np
np.set_printoptions(formatter={'int':hex})
np.array([1,2,3,4,5])

gives

array([0x1L, 0x2L, 0x3L, 0x4L, 0x5L])

The L at the end is just because I am on a 64-bit platform and it is sending longs to the formatter. To fix this you can use

np.set_printoptions(formatter={'int':lambda x:hex(int(x))})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...