PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

[FIXED] How to convert integer numbers read from a text file and store as a binary file having 16bit integers?

 August 12, 2022     binary, decimal, python, python-3.x     No comments   

Issue

trying to read decimal values from text file convert into 16-bit binary and into a binary file.

Sample input file

120
300
-250
13
-120

Code:

def decimaltoBinary(filename,writefile):
    file = filename
    print(file)
    file_write = open(writefile,'wb')
    file_read = open(file, 'rb')
    for line in file_read:
        value = int(line)
        if value < 0:
            binary_value = bin((2**16) - abs(value))[2:].zfill(16)
            file_write.write(binary_value + "\n")
        else:
            binary_value = bin(int(value))[2:].zfill(16)
            file_write.write(binary_value + "\n")
    file_write.close()

decimaltoBinary(input_file.text,output_file.bin)

Hoping to write the converted decimal values into a binary file.. any help is much appreciated


Solution

You can use the struct module for that:

data = [120,300,-250,13,-120] # you seem to have the reading part covered already
                              # using a list as data input for demo purposes
import struct

with open("f.bin","wb") as f: 
    for d in data:
        f.write(struct.pack('h', d)) # 2 byte integer aka short

with open("f.bin","rb") as f:
    print(f.read())  # b'x\x00,\x01\x06\xff\r\x00\x88\xff'

You just need to specify 'h' to get short (2-byte integer) packing.

For the weird print output blame python - it replaces "known" \xXX codes with shorter normal characters - f.e. ',' => 0x2c or \r => \x0d etc.



Answered By - Patrick Artner
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing