Numpy Int Array to HEX and then to String Conversion PYTHON
<p>I have couple of questions </p>

<p>Say I have a numpy array </p>

<pre><code>a = np.array([0,1,2,3,4,31])

a0 = a[0]
a1 = a[1]
a2 = a[2]
a3 = a[3]
a4 = a[4]
a5 = a[5]


print hex(a4), hex(a5)
</code></pre>

<p>gives me </p>

<pre><code>   0x4L 0x1F
</code></pre>

<p>same for a0, a1, a2, a3,a5. I know the L is because of the numpy array. </p>

<p>Now how would I get 0x04 and not 0x4. </p>

<p>My required outcome is </p>

<pre><code>'0x1F0403020100'
</code></pre>

<p>My required answer should start with 0x -- the hex values of a5, a4, a3, a2, a1, a0 - without the OX. The required output is a string. I can do the bit manipulation, if I have the zero. But not without it. </p>

<p><strong>tl;dr</strong></p>

<pre><code>("0x" + ("{:0&gt;2x}" * len(a))).format(*tuple(a[::-1]))
</code></pre>

<p><hr>
<strong>Explanation:</strong></p>

<ul>
<li><p>Multiply string <code>"{:0&gt;2x}"</code> a number of times equal to <code>len(a)</code>, i.e. do <code>"{:0&gt;2x}" * len(a)</code>. This will create the following string:</p>

<pre><code>'{:0&gt;2x}{:0&gt;2x}{:0&gt;2x}{:0&gt;2x}{:0&gt;2x}{:0&gt;2x}'
</code></pre>

<p><code>{:0&gt;2x}</code> used inside  a string can later be formated using the <code>.format</code> method, resulting in a translation of an int into a hexadecimal string, of width 2, where any padding is done with <code>0</code>.<br>
Multiplying by the length of the array means you can create that many hex-formatted arguments.</p></li>
<li>Concatenate / prefix this string by <code>"0x"</code></li>
<li>Reverse your array, since you want it reversed, by doing <code>a[::-1]</code></li>
<li>Put the reversed array into a tuple, i.e. <code>tuple(a[::-1])</code>.</li>
<li>Expand this tuple using * syntax to make it into method arguments, i.e. <code>*tuple(a[::-1])</code></li>
<li>Now you can use the expanded tuple as an argument to the <code>.format</code> method, on the concatenated string you created containing the custom formatting the correct number of times.</li>
</ul>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; ("0x" + ("{:0&gt;2x}" * len(a))).format(*tuple(a[::-1]))
'0x1f0403020100'
</code></pre>

<p>PS. If you prefer capital hex strings, replace <code>x</code> with <code>X</code>, i.e.:</p>

<pre><code>&gt;&gt;&gt; ("0x" + ("{:0&gt;2X}" * len(a))).format(*tuple(a[::-1]))
'0x1F0403020100'
</code></pre>

python arrays string numpy