Можно ли в 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
🎧⤴
TON Foundation Collaborates with Curve Finance to Incubate Stable Swap Project
The TON Foundation has teamed up with Curve Finance to incubate a TON-based stablecoin swap project, aiming to revolutionize stablecoin trading on the TON blockchain. With the demand for stablecoins on TON rapidly growing, and USDt reaching $729.9 million in circulation, this initiative will improve liquidity and enhance the Web3 ecosystem. By leveraging Curve’s CFMM technology, the collaboration seeks to streamline stablecoin swaps and minimize price impacts. With Michael Egorov advising, the selected independent team is set to innovate.
Chorus:
We’re buildin’ up the TON, it’s the next step on,
With Curve at our back, we’re never gone.
Stablecoins swap, yeah, the flow’s so strong,
In the blockchain game, we gon’ last long.
Verse 1:
TON's the name, we rise, no fear,
Curve in the mix, DeFi pioneers.
Stablecoin swaps, make it clear,
Liquidity’s high, the future’s near.
CFMM tech, smooth like silk,
Price impact low, no need for guilt.
USDt growin’, millions in sight,
We’re buildin’ the future, shine so bright.
Chorus:
We’re buildin’ up the TON, it’s the next step on,
With Curve at our back, we’re never gone.
Stablecoins swap, yeah, the flow’s so strong,
In the blockchain game, we gon’ last long.
Verse 2:
From Telegram roots, we took the chance,
Sharding the blocks, a future dance.
Transactions fast, like a lightning glance,
In the Web3 world, we enhance.
Michael’s guidance, we push the plan,
TON’s the network, we take a stand.
Curve’s design, it’s the DeFi brand,
Together we rise, hand in hand.
Chorus:
We’re buildin’ up the TON, it’s the next step on,
With Curve at our back, we’re never gone.
Stablecoins swap, yeah, the flow’s so strong,
In the blockchain game, we gon’ last long.
Verse 3:
Apply today, join the crew,
The future’s here, and it’s made by you.
Swappin’ coins with a vision so true,
Decentralized world, we break through.
Millions waitin’, it’s time to act,
With TON and Curve, there’s no turnin’ back.
Liquidity surgin’, that’s a fact,
The TON foundation is on track.
Chorus:
We’re buildin’ up the TON, it’s the next step on,
With Curve at our back, we’re never gone.
Stablecoins swap, yeah, the flow’s so strong,
In the blockchain game, we gon’ last long.
Bridge:
Innovation’s key, we’re set to soar,
With TON and Curve, there’s so much more.
Stablecoins movin’, open the door,
To a DeFi future we can’t ignore.
#TONFoundation
#Curve
#TONCryptoNewsRapStyle
We start the year with another event — SE Telegram Builders Day in Hong Kong from @epicweb3!🪭
The day before Consensus HK starts, speakers from #Blum, #TerminalStation, #AnimocaBrands, #StormTrade, #Fintopio, #TONFoundation and other projects will gather on one stage.
Participants will discuss the latest trends, attracting users and investments, secrets of viral projects, the future of the ecosystem and much more that awaits us in 2025.
The event is FREE, but places are limited, so hurry if you want to join.
🗓️February 17, Hong Kong
🎫Get a free ticket👈
The Future of Toncoin
One of the popular channels published a post under which users were asked to answer the question "What is missing in 🤑 TON?" For your convenience, all ideas are grouped into categories and repetitions are removed.
⚡️Infrastructure and technical improvements
🔵 Improving transaction speed and network performance (relevant for swaps, DEX and bridges), in real conditions under heavy load and not just on a test bench.
🔵 Official bridge to other blockchains (Ethereum, BSC, Solana, L2 Ethereum, etc.).
🔵 Optimization of oracles in bridges (so that transfers do not take from 7 hours to 12 days).
🔵 Launch of the official mempad by the TON Foundation. *TON Memelandia was launched last year, did not have much impact on TON.
🔵 Improving MEV bot algorithms, including mechanisms for returning part of the funds to users.
🔵 Introduction of limit orders on DEX and aggregators.
🔵 Improving support for existing projects and infrastructure.
🔵 Optimization of smart contracts to protect users (auto-vesting, prohibition of instant withdrawal of liquidity, etc.).
🔵 Developing a visual designer for dApps and mini-applications in TON (simplifying entry for new developers).
🔵 Optimization of Telegram Wallet and improvement of TON integration into #Telegram.
🔵 Reduced transaction fees.
⚡️DeFi Development
🔵 More liquidity in the $TON ecosystem.
🔵 Access to major tokens ($ETH, $BTC, $SOL) on #DEX.
🔵 Liquidity pools with the ability to use three or more tokens.
🔵 Simplifying the #P2P marketplace and improving user instructions.
🔵 Introduction of TON Pay and TON Business for convenient payments within the ecosystem.
⚡️Anti-fraud and transparency
🔵 Creation of a department to combat fraud within TON.
🔵 Checking token creators before launch (registration, reputation ratings).
🔵 A mechanism for quickly blocking scam channels and projects in Telegram.
🔵 Improving the transparency of the #TONFoundation and Telegram Mini Apps (disclosure of commands, #AMA sessions, public reports).
🔵 Introduction of risk insurance and user protection when investing in TON.
⚡️Marketing and expansion
🔵 Scaling TON beyond the CIS (China, USA, Europe, Latin America).
🔵 Creation of official TON accounts on Weibo and other social networks for the Chinese audience.
🔵 Implementation of TON in large services.
🔵 Active work with bloggers and media to attract new users.
🔵 Improving educational programs and guides on TON.
🔵 Conducting large partnerships (for example, with Telegram Premium, marketplaces and gaming platforms).
⚡️DAO, NFT and new mechanics
🔵 NFT marketplace with real digital assets (music, files, tokenization).
🔵 Gaming projects on TON with real monetization.
🔵 Tools for creating DAOs and custom #NFTs.
🔵 Integration of #Web3 authorization via Telegram.
🔵 Creating SocialFi initiatives and user reward mechanisms.
🔵 Launch of a #DeFi center inside TON (built-in swaps, staking, farming, #DAO).
⚡️General ideas
🔵 Selling concert tickets in #NFT format with gamification (VIP upgrades, voting for tracks, digital rewards). * this idea is already being implemented by at least 2 projects, well-known editors.
🔵 SBT reward payouts and ecosystem activity.
🔵 Launch of a "kickstarter" to finance new projects in #TONwith the support of the community.
🔵 Creating internal tokens with real utility, not just speculative instruments.
🔵 Introducing an additional token burning mechanism for economic sustainability.
🔄To summarize, most of the participants in the discussion believe that TON needs:
👍Improving technical infrastructure (bridges, speed, liquidity, DEX, DeFi).
👍Improving security and combating scams (anti-fraud department, project verification).
👍Global expansion (China, USA, Europe, partnerships).
👍Marketing initiatives (media, bloggers, educational programs).
👍Development of new products (DAO, NFT, SocialFi, Web3).
👍Transparency and openness of the TON Foundation.
Despite the current difficulties, TON has the potential for explosive growth🤟, if it focuses on DeFi, mass adoption and game mechanics.
⚡️Boost | 🎞YouTube | 𝕏 Twitter