Write hex code to text file from integer value in python

Question!

Details: Ubuntu 14.04(LTS), Python(2.7)

I want to write hex code to a text file so I wrote this code:

import numpy as np

width = 28    
height = 28
num = 10

info = np.array([num, width, height]).reshape(1,3)
info = info.astype(np.int32)

newfile = open('test.txt', 'w')
newfile.write(info)
newfile.close()

I expected like this:

00 00 00 0A 00 00 00 1C 00 00 00 1C

But this is my actual result:

0A 00 00 00 1C 00 00 00 1C 00 00 00

Why did this happen and how can I get my expected output?

By : 이태우


Answers

If you want big endian binary data, call astype(">i") then tostring():

import numpy as np

width = 28    
height = 28
num = 10

info = np.array([num, width, height]).reshape(1,3)
info = info.astype(np.int32)
info.astype(">i").tostring()

If you want hex text:

" ".join("{:02X}".format(x) for x in info.astype(">i").tostring())

the output:

00 00 00 0A 00 00 00 1C 00 00 00 1C
By : HYRY


You mention multiple text boxes so to avoid repeating the same code for each one I'd probably recommend doing it as a loop. I started doing this as am "empty" check on the _POST var but then realised that, if you need the answers to be a number then !is_numeric() is a better way to ensure they provide a number too.

// Textbox field names
$myPostedTextBoxes = Array("usernumber","anotherbox1","anotherbox2");

// Convert empty values to "0"
foreach($myPostTextBoxes as $tb){
    $_POST[$tb] = !is_numeric($_POST["tb"])?"0":$_POST[$tb];
}


if you using post method then you can check like this

$missed = 0;
$usernumber =$_POST['usernumber'];
if($usernumber=='')
{
  $usernumber = $missed;
}


This video can help you solving your question :)
By: admin