Можно ли в Python создавать бинарные файлы? Конечно можно.
Для этого в Python есть следующие инструменты:
▫️ тип данных bytes и bytearray
▫️ открытие файла в режиме wb (write binary) или rb (read binary)
▫️ модуль struct
Про модуль struct поговорим в первую очередь.
Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных.
В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла.
Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла.
Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид.
Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки).
Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение.
При этом следует помнить что мы говорим о типах языка С а не Python.
Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще.
Вот какие токены формата у нас есть.
Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы.
В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты.
Запакуем в байты простое число, токен "i".
>>> import struct
>>> struct.pack('=i', 10)
b'\n\x00\x00\x00'
Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов.
>>> struct.pack('=fff', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же.
>>> struct.pack('=3f', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Теперь запакуем разные типы
>>> data = struct.pack('=fiQ', 1.0, 4, 100500)
я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт)
b'\x00\x00\x80?\x04\x00\x00...'
Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа.
>>> struct.unpack('=fiQ', data)
(1.0, 4, 100500)
Как видите, ничего страшного!
#lib#basic
🚀$BOOM IDO on #TonUP Confirmed!
🎮BOOM UP: The first MiniApp on The Open Network with construction, social interaction, and profitability. Enjoy mobile gameplay with assets secured on TON blockchain.
💎 IDO Rounds:
• Community Round: July 11th, 10:00 AM - 12:00 PM UTC. Exclusive for active community members.
• UPer Round: July 11th, 12:00 PM - July 12th, 12:00 PM UTC. Open to $UP token holders. Hold and stake $UP for rewards and allocation.
The $BOOM IDO price details and single whitelist participation amounts will be gradually revealed.
🤔 What is TonUP?
🚀 Big News from #TonUP!
The Upgraded UPbassador Program has just launched! This initiative is a testament to TonUP's deep appreciation for the dedication and passion of its community builders. If you share their vision for the evolving #TON ecosystem, now is the perfect time to join their mission.
💎 Key Enhancements:
• Enhanced rewards with $UP tokens and exclusive early access rights.
• New roles and tracks for those interested in contributing to TonUP.
• Improved support and resources to ensure your success.
🔗 Ready to make a lasting impact? Join the UPbassador Program
🤔 What is TonUP?
Dear BYINLords, Big News is coming!
🚀 The $BYIN IDO is now confirmed for August 26th on #TonUP, the leading launchpad of #TON!
The $BYIN IDO will be offering three rounds this time:
1⃣️ August 26th UTC 10:00 AM - 11:00 AM, KOL & Community Round:
This exclusive round is reserved for active community members and key opinion leaders. Stay tuned to our social channels for details.
2⃣️ August 26th UTC 11:00 AM - 13:00 PM, UPer Round:
This round is open only to $UP token holders. To participate, simply hold and stake your $UP to earn token rewards and potential allocation. We will announce the staking details soon.
3⃣️ August 26th UTC 13:00 PM - August 27th UTC 13:00 PM, Public Round:
This round is open to all users with limited allocation. The $BYIN IDO price details and participation amounts will be gradually revealed.
🔗 For more IDO details, please visit: https://tonup.io/project/BYIN
https://x.com/TonUP_io/status/1825558366082732165
👀 Stay tuned for more upcoming big news!
🔥 As the leading launchpad on the TON blockchain, #TonUP is pleased to disclose changes to the revenue distribution model for the platform's revenue.
Going forward, all the platform revenue generated from IDO service fees will be allocated as follows:
⚫️ 25% will be used to provide #IDO tokens to the Launchpool program for the benefit of $UP token holders.
⚫️ 50% will be earmarked for $UP token buyback and burns, reducing the overall circulating supply of $UP.
⚫️ 25% directed towards supporting the #TonUP team
It's important to note that future IDO participants will no longer receive $UP tokens as a reward.
🔗 To maintain transparency, TonUP will regularly update the community on buyback and burn details on this page.
🔥 All transactions from the tonup-buyback.ton wallet will also be publicly disclosed.
❤️ This new model is designed to better align incentives and provide greater value to our holders. The TonUP team looks forward to sharing more updates soon.
🚀 BOOM UP Successfully Concludes IDO on #TonUP!
📅 Claim Your $BOOM Tokens:
Date: July 15th
Time: 03:00 AM UTC
💙 Exciting News! $BOOM will be listed on Bitget, a leading global cryptocurrency exchange, fulfilling their #CPP commitment.
🔵 Initial Listing Details:
Trading Pair: BOOM/USDT
Deposit: Now Open
Trading Starts: July 15 at 12:00 PM UTC
🤔 What is TonUP?
🚀 The $BYIN IDO is now confirmed for August 26th on #TonUP!
🎮@BYINchann is a gateway to effortlessly creating and trading memecoins on #TON. It offers features like easy token creation, on-platform fundraising, dynamic pricing, and seamless #DEX integration. The platform also provides Telegram-based tools like reminders, trending alerts, and management bots.
The $BYIN IDO will be offering three rounds this time:
1️⃣August 26th UTC 10:00 AM - 11:00 AM, KOL & Community Round: This exclusive round is reserved for active community members and key opinion leaders. Stay tuned to the social channels for details.
2️⃣August 26th UTC 11:00 AM - 13:00 PM, UPer Round: This round is open only to $UP token holders. To participate, simply hold and stake your $UP to earn token rewards and potential allocation. Staking details will be announced soon.
3️⃣August 26th UTC 13:00 PM - August 27th UTC 13:00 PM, Public Round: This round is open to all users with limited allocation. The $BYIN #IDO price details and participation amounts will be gradually revealed.
🫥For more IDO details, please visit: tonup.io/project/BYIN
🫥 For more project info, please check: community.tonup.io/t/all-you-need-to-know-about-byin-ido
💎 The BYIN IDO is committed as part of the #TonUP CPP program, offering a comprehensive refund policy if the $BYIN token price dips below the IDO price. So don't miss out on this chance with a full promise of protection!
We will give 1 WL's to KOL & Community Round to the one who left more 🌟 Stars under this post
TonUP | Chat | Blog | X | Website
🎊SnakeLite x TonUP x BYIN
🚀 $BYIN IDO will go live on AUG 26th on #TonUP!
💎 $BYIN IDO on TonUP is under Community Protection Plan (CPP), with Refund Policy, Liquidity Supervision and Price Protection.
🎁2✖️WL for Community Round of #BYIN IDO #Giveaway
🔥Participate NOW
https://x.com/snakeliteio/status/1826869554343182645
⏰12H
✅Join https://t.me/BYIN_official_bot
✅Join https://t.me/Snakelite_official_bot
WL holders can participate in KOLs & Community Round of BYIN IDO on TonUP directly, and no need to stake $UP (the token of TonUP) before IDO.
Details about IDO WL: https://bit.ly/3X9oMl9
Details about IDO CPP: https://bit.ly/3yNmQFs
The Highly Anticipated $BOOM IDO on TonUP is now CONFIRMED!✔️
👾BOOM UP is the first lightweight Mini App integrated with construction, social interaction, and strong profitability, all built on The Open Network. It allows players to experience the joy of play on their mobile devices, with assets secured on the #TON blockchain.
💎 The #BOOM#UP#IDO is an integral part of the #TonUP CPP program, offering a comprehensive refund policy if the $BOOM token price dips below the IDO price.
For the IDO will be offered two rounds with new mode:
💎Community Round:July 11th, 10:00 — 00:00 UTC
This exclusive round is reserved for our active community members and key opinion leaders. Stay tuned to the official social channels for details on how to earn a spot.
💎UPer Round: July 12th, 00:00 — July 13th, 00:00 UTC
This round is open only to $UP token holders. To participate, simply hold and stake your $UP to earn token rewards and potential allocation. TonUP will announce the staking details soon.
The $BOOM IDO price details and single whitelist participation amounts will be gradually revealed.
🔗For more IDO detailed information, check this
🎓For more project info and updates, check this
Announcement | Chat | Website