Wednesday, September 22, 2010

Python and binary data - Part 3

Normal file operations that we use are line oriented
FILE = open(filename,"w")
FILE.writelines(linelist)
FILE .close()
FILE = open(filename,"r")
for line in FILE.readlines(): print line
FILE .close()

We can also use byte oriented I/O operations on these files.
FILE = open(filename,"r")
FILE.read(numBytes)  # This reads up to numBytes of Bytes from the file.
But if the file does not contain textual data, the contents may not be meaningful.

It is much better to open the file in binary mode
FILE = open(filename,"rb")
FILE.read(numBytes)



Python objects and "C" struct storage
Python does provide a different abstraction level than "C" for the various data types like integer etc. They also store them differently.
Of course the data stored in binary files or sent and received across the network is contiguous bytes. In Python, the data like list may not be stored as contiguous chunk of bytes.
C variable
     +-----+         +--------+
     |array|-------> |10|9|2|3|
     +-----+         +--------+
                     contiguous bytes

Python variable

     +-----+         +-------+
     |array|-------> |.|.|.|.|
     +-----+         +-------+
                      | | | |
                      | | | |
                     10 9 2 3


To handle them, it is important to convert python values to "C" structs, i.e pack them as contiguous bytes of data or dissemble a contiguous chunk of bytes to Python objects.

The module "struct" provides facility to pack python objects as contiguous chunk of bytes or dissemble a chunk of bytes to python structures.

Packing a structure
The pack function takes a format string and one or more arguments, and returns a binary string. This looks very much like you are formatting a string except that the output is not a string but a chunk of bytes.
import struct
import sys
print "Native byteorder: ", sys.byteorder
# If no byteorder is specified, native byteorder is used
buffer = struct.pack("ihb", 3, 4, 5)
print "Byte chunk: ", repr(buffer)
print "Byte chunk unpacked: ", struct.unpack("ihb", buffer)
# Last element as unsigned short instead of unsigned char ( 2 Bytes)
buffer = struct.pack("ihh", 3, 4, 5)
print "Byte chunk: ", repr(buffer)
Output: 

Native byteorder:  little
Byte chunk:  '\x03\x00\x00\x00\x04\x00\x05'
Byte chunk unpacked:  (3, 4, 5)
Byte chunk:  '\x03\x00\x00\x00\x04\x00\x05\x00'

You could use network byte order with data received from network or pack data to send it to network.

import struct
# If no byteorder is specified, native byteorder is used
buffer = struct.pack("hhh", 3, 4, 5)
print "Byte chunk native byte order: ", repr(buffer)
buffer = struct.pack("!hhh", 3, 4, 5)
print "Byte chunk network byte order: ", repr(buffer)
Output:
Byte chunk native byte order:  '\x03\x00\x04\x00\x05\x00'
Byte chunk network byte order:  '\x00\x03\x00\x04\x00\x05'

You can optimize by avoiding the overhead of allocating a new buffer by providing a buffer that was created earlier.

import struct
from ctypes import create_string_buffer
bufferVar = create_string_buffer(8)
bufferVar2 = create_string_buffer(8)
# We use a buffer that has already been created
# provide format, buffer, offset and data
struct.pack_into("hhh", bufferVar, 0, 3, 4, 5)
print "Byte chunk: ", repr(bufferVar.raw)
struct.pack_into("hhh", bufferVar2, 2, 3, 4, 5)
print "Byte chunk: ", repr(bufferVar2.raw)

Byte chunk:  '\x03\x00\x04\x00\x05\x00\x00\x00'
Byte chunk:  '\x00\x00\x03\x00\x04\x00\x05\x00'

Unpacking , of course is the reverse of packing : unpack(fmt, binary).



55 comments:

  1. The knowledge of python is very essential for the software developers. Python is a high level, general purpose, dynamic programming language that is of code readability and its synatx allows programmers to express the concept in fewer lines of code.
    python training in chennai | python training institutes in chennai

    ReplyDelete
  2. Very good article on using struct. Thank you.

    ReplyDelete
  3. Nice information about python and the programming structure is explained in an understandable manner my sincere thanks for sharing this post
    Python Training in Chennai

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Really i found this article more informative, thanks for sharing this article! Also Check here
    CCC Result 2020

    ReplyDelete
  6. Thanks for sharing information awesome blog post Online Education Quiz website For Exam Follow this website Gk in Hindi

    ReplyDelete
  7. we are here for you guys to enhance your skills during this period. Our institution offering you CS executive classes and free CSEET classes. So guys for more info contact us or visit us at website https://uniqueacademyforcommerce.com/

    ReplyDelete
  8. The Universal Currency Converter Is The Most Reliable And Accurate CHF USD Currency Conversion Tool On The Internet. It Is Fast And Easy To Use, And Supports Over 150 World Currencies.

    ReplyDelete
  9. AximTrade Offers A Safe And Secure Platform To Do Forex Trading And CFDs And Our Customer Support Is Ready To Help You 24/7. You Can Easily Sign Up Your Aximtrade Login Account Here.

    ReplyDelete
  10. XM REVIEW If You Are A Beginner, Check Out Our Guide On How To Open An Account With XM. They Offer Copy Trading Where You Can Copy The Trades Of Successful Traders.

    ReplyDelete
  11. AVATRADE REVIEW Is A Relatively New Forex Broker, Which Offers Its Customers A Wide Range Of Trading Opportunities. Read All The Facts About This Broker In This Detailed Fx Choice Review.

    ReplyDelete
  12. Do you want to rank higher in Google's search results? You might be thinking "how do I get backlinks?" Tradingzy is the best company that specializes in Backlink Services . We have over years of experience in the industry and have ranked our clients' websites on the first page of Google. The backlink services we offer are guaranteed to give you the results you are looking for. The quality of our backlinks is what sets us apart from other companies.

    ReplyDelete
  13. Backlink Services are a quick and easy way to increase the visibility of your website on the internet. There are many types of backlinks that you can purchase, including forum posts, blog posts, articles, press releases, social media posts, and more. We have the experience and expertise to create the perfect backlink for your needs.

    ReplyDelete
  14. I hope you're doing really well and enjoying the day ahead. We are a Digital Marketing agency focusing on Marketing Forex . We have been on top of Google search for the phrases you can see on the right and we will be happy to tell you how we did it.

    ReplyDelete
  15. Broker Forex Net Is Focused On Giving You The Right Details About Online Trading. The Website Was Created By Top-tier Traders With Years Of Experience In The Financial Markets. We're Committed To Providing Objective, Practical Information About Broker Services And Trading Strategies So You Can Make Better Decisions About Your Investments.

    ReplyDelete
  16. Get the latest Siml Stock price with our real-time quote and chart. Check the performance of siml stock with historical data and read summary analysis on this stock in Our Servlogin Webpage.

    ReplyDelete
  17. Market Forex Net Is The Best Place To Research And Compare Brokerages. We've Worked Hard To Find You The Best Brokers In Terms Of Commissions, Minimum Deposit, And Account Restrictions. Our Mission Is To Make It Easier For The Average Investor To Find, Compare And Review The Best Brokers On Their Own Time.

    ReplyDelete
  18. Servlogin is a leading website for comprehensive data and analysis on Harris Teeter Ess . On this site you'll find daily updates on the latest trends shaping today's market, as well as in-depth reports from team of expert analysts who have been tracking these stocks for years. We break down the deals so you can make an informed decision about your investment. If you are considering a purchase or an initial public offering of Harris Teeter Ess, then check out our special reports section.

    ReplyDelete
  19. Stay In Touch With fxit stock? Every Move With Our Live, Real Time Stock Market Overview. Here You Will Always Be One Of The First To Know When fxit stock Is Increasing Or Decreasing. Our Live Information Is Delivered Right To Your Browser, Giving You All The Data You Need To Make An Informed Trading Decision. With This Information At Your Fingertips You Will Be Able To Make Quick And Educated Decisions While Keeping Track Of All The Latest Sos Stock Price Changes!

    ReplyDelete
  20. No One Knows How Many Links Are Required To Rank On The First Page Of Google, But It's Safe To Say That There Are A Lot. We Will Do All The Work For You, Including The Tedious Crypto Seo Services Process, For A Reasonable Price. We'll Make Sure That You Have A Complete List Of Links, Both Old And New, To Keep Your Site's Rankings High.

    ReplyDelete
  21. Never miss a stock price change from Gmhi Stock with our Live, Real Time Stock Market Overview! Most of the data is updated every 5 minutes to ensure that you are getting all of the latest Acam Stock change alerts as soon as they happen.

    ReplyDelete
  22. Forex Trading Cost is a comprehensive guide to deciding on the best Forex Brokers, Trading Costs and Fees. Find out which brokers offer the best value for money?

    ReplyDelete
  23. You'll understand the market a whole lot better with the data and graphic tools provided by our stock quote system. You'll understand how certain economic events can affect your investments, and be able to answer questions from stock market friends concerning when to buy or sell Sos Stocktwits . You will have access to live charts, and you can receive instant notifications as stocks change in cost.

    ReplyDelete
  24. You'll understand the market a whole lot better with the data and graphic tools provided by our stock quote system. You'll understand how certain economic events can affect your investments, and be able to answer questions from stock market friends concerning when to buy or sell Mmjff . You will have access to live charts, and you can receive instant notifications as stocks change in cost.

    ReplyDelete
  25. If you are looking to find the best place where to buy Where To Buy Ubx Coin , you have come to the right place. Ubx Coin has received a lot of attention lately because 1 coin = $1.00 USD. Because of this, we felt it was necessary to put together a guide that offers you information about UBX and ways that you can buy it.

    ReplyDelete
  26. Truff Stock Get free stock market quotes, stock information, company news, historical charts and financial overviews from Truff Stock . We bring you all the latest Truff Stock market & financial news All in one place.

    ReplyDelete
  27. Bfarf stock Real-Time Overview Of A Stock, Including Recent And Historical Price Charts, News, Events, Analyst Rating Changes And Other Key Stock Information.

    ReplyDelete
  28. Ftoc Stock Overview: Stay ahead of the market with our live and real time stock market overview. Get all of your favorite stocks in one place, and get alerted to live news at the same time!

    ReplyDelete
  29. The most comprehensive guide to Forex Brokers and How To Start Forex Broker , showing you what you can save or earn by choosing the best broker for your needs – from Highest to Lowest Charges. Useful for both beginner and seasoned trader.

    ReplyDelete
  30. Are you looking to make money by trading currencies on the forex market? Do you want to find the best forex brokers with the lowest costs and fees? Our free guide provides all the information you need to start trading, selecting a reputable and safe broker, and understanding your How To Start Forex Brokerage .

    ReplyDelete
  31. The Dbd Forums Overview offers real time stock price updates. All you need to do is open the application and you can view Streaming stock prices of your favorite stocks.

    ReplyDelete
  32. Ati testing login Overview: Stay ahead of the market with our live and real time stock market overview. Get all of your favorite stocks in one place, and get alerted to live news at the same time!

    ReplyDelete
  33. Stay on top of the market with our Live, Real-Time Stock Market overview. Get real time Fxit Stock quotes and interactive charts.

    ReplyDelete
  34. Gteh Stocktwits Overview: Stay ahead of the market with our live and real time stock market overview. Get all of your favorite stocks in one place, and get alerted to live news at the same time!

    ReplyDelete
  35. As a new forex trader you need to know what the best brokers offers and their How To Create Your Own Broker before you begin trading and investing, Use this guide to learn about trading costs, leverage and leverage limits, spreads and execution times, custodial services and market maker spreads .

    ReplyDelete
  36. Free Forex White Label Partnership is an online forex trading course designed for beginner traders to learn basic and advanced techniques of the forex market. The course is divided into 10 modules that cover topics such as risk management and position sizing strategies along with highly profitable algorithmic trading strategies.

    ReplyDelete
  37. White Label Partnership Forex will enable you to get all the benefits of the MetaTrader 4 automated trading platform and MetaQuotes language with even more exciting functionalities for your own brand

    ReplyDelete
  38. Cheapest White Label Forex Broker will enable you to get all the benefits of the MetaTrader 4 automated trading platform and MetaQuotes language with even more exciting functionalities for your own brand

    ReplyDelete
  39. If you have been looking for facts about what is forex seo and how it works, Then tradingzy is the best and most reliable place. becouse tradingzy is Digital Marketing agency focusing on Forex Seo.

    ReplyDelete
  40. At Tradingzy, we can help you learn what is forex seo and how to use it. We're a digital marketing agency focusing on SEO for the Forex Brokerage company. We're familiar with Google's updates and how to work with them effectively.

    ReplyDelete
  41. If you have been looking for facts about What Is Liquidity In Cryptocurrency and how it works, Then tradingzy is the best and most reliable place. because tradingzy is Digital Marketing agency focusing on Forex Seo.

    ReplyDelete
  42. At Tradingzy We can help you learn What is Forex SEO and how to use it. We are a Digital Marketing agency focusing on Forex Seo. We have been on top of Google search for the phrases you can see on the right and we will be happy to tell you how we did it.

    ReplyDelete
  43. If you’ve been looking for information on What is Forex SEO , then tradingzy is the best place for you. We’re a digital marketing agency specializing in forex seo strategy.

    ReplyDelete
  44. Forex trading is one of the fastest growing markets. Forex Seo will teach you how to trade forex like a pro. It contains some of the best strategies for learning a six-figure income in your spare time with very little financial risk.

    ReplyDelete
  45. "Forex Seo Services will help you increase your business by reaching the maximum number of potential customers through social media, Search Engines and direct advertisement.

    ReplyDelete
  46. Best Regulated Forex Brokers In Samoa Based On Independent Ratings, Reviews, And Online Presence. Find Out Which Broker You Should Choose.

    ReplyDelete
  47. CMC Markets Review Is A Great Trading Platform, But Is It The Best? Read This Review To See If It Is The Right Option For You.

    ReplyDelete
  48. This is our list of the Best MT4 Forex Brokers In UAE . Each broker has been carefully selected and reviewed before appearing on this list. We take pride that all of the brokers listed pay their affiliates promptly and give you excellent trading education.

    ReplyDelete
  49. Would You Like To Access Your Top Forex Brokers In Malaysia Account And Manage Your Trades? This Is The Place For You. Here You Can Easily Manage Your Investments, Deposit Or Withdraw Funds. Read More Here.

    ReplyDelete