Можно ли в 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
⚡️Trending Apps: Insights from Arkham Founder
#Telegram#Arkham
Trending Apps shared highlights from an insightful conversation with Arkham's founder. Arkham is leveraging Telegram to enhance its blockchain analytics Mini App, aiming to make whale activity analysis intuitive and mobile-friendly. They plan real-time alerts and deeper Telegram integrations, targeting the TON audience for growth.
Source: link
@tonlines
Trending Apps: Arkham Now Available on Telegram
#Telegram#Arkham
Trending Apps introduces Arkham in the Telegram Apps Center, allowing users to set alerts, track traders, and earn points without leaving the chat. This mini-app facilitates seamless on-chain tracking with just one button.
Source: link
@tonlines
TON — LIVE: Arkham Launches Telegram App
#Arkham#Telegram#TON
Arkham has launched a new application in Telegram, enhancing the ability to track on-chain data in the TON ecosystem. Users can analyze trading activities, major transfers, and various network activities using time filters and label management options.
Source: link
@tonlines
⚡️Trending Apps: Arkham AMA Session Announcement
#Arkham#blockchain
Trending Apps announces an Arkham AMA session featuring the Founder & CEO. This event, scheduled for May 30 at 17:00 UTC on Trending Apps' X account, will provide exclusive insights into Arkham's roadmap and future plans.
Source: link
@tonlines
Arkham launched Telegram Mini-App!
Arkham is a leading on-chain analytics platform that tags addresses, tracks connections between them, and identifies key participants in the blockchain.
Yesterday, the project team announced the launch of its analytical platform in the format of a Telegram application. In the application, you can search for data by addresses: the Arkham database contains 2.1 billion tagged accounts and 700 thousand entities, as well as create and manage notifications about any on-chain transactions directly in Telegram.
✈️Arkham Telegram mini-app
#TON#Arkham#Analytics
🇬🇧Arkham Horror_The Terror at the End of Time #1-2
🇷🇺Ужас Аркхэма_Ужас в конце времён #1-2
Дженни Барнс, авантюристка и светская дама, считала жизнь одной большой игрой. Но всё изменилось, когда опасный культ похитил её сестру. Хоть Дженни и помешала жертвоприношениям культистов, и даже сразилась с жуткими монстрами по их приказу, верховная жрица Эбигейл Олмстед сбежала, забрав Иззи с собой.
#комикс#comics#аркхэм#arkham
#dark_horse
🚀 Alameda Research Transfers $16 Million in SOL to Creditor Distribution Address
According to Odaily, Arkham has reported that Alameda Research has unstaked $16 million worth of SOL and transferred it to an address designated for creditor distribution. This marks the first such transaction in a month.
#AlamedaResearch#SOL#Crypto#Cryptocurrency#Blockchain#CreditorDistribution#Arkham#DeFi
Satoshi Nakamoto Identity Clue?
Coinbase's Conor Grogan claims Kraken may hold clues to Satoshi Nakamoto’s identity. Analysis of wallet clusters revealed a past transaction from the Canadian exchange CaVirtEx, acquired by Kraken in 2016. Doubts arise over KYC compliance; transaction may involve any user, not necessarily Satoshi. Current Arkham data shows Satoshi’s 22,000 wallets contain 1.09M BTC, valued at $107B.
Links: News | AI | YouTube
#Satoshi#Kraken#AI#Crypto#Blockchain#Bitcoin#Coinbase#P2P#Wallets#Arkham#BTC#KYC
ETH Deposits Surge on Bybit
Aave's ETH supply surpassed 2M for the first time. Mirana Ventures deposited $600M worth of ETH into Bybit, becoming the largest depositor since the hack. The firm sold $500M in Bitcoin and $100M in USDT to fund this. In addition, $130M in USDT transferred to Tether Treasury. Significant BTC movements reported as well. Full details in the links: Arkham, The Block, Whale Alert USDT Transfer.
#ETH#Aave#Bybit#Crypto#USDT#BTC#MiranaVentures#DeFi#Arkham#Treasury#GameStop#SEC#Uniswap#AlgorithmicTrading#Blockchain#Investments#Bitcoin#WhaleAlert#Fintech#VC
Bybit's Major ETH Acquisition Revealed
Bybit addresses crypto hack fallout:
- ETH purchase of 36,900 from 100M USDT transfer to Galaxy Digital and FalconX.
- Involved suspected address: 0x2E...1b77.
- CEO acknowledges support from various companies post-hack.
- Allegations of North Korean hackers tied to Bybit hack confirmed by Arkham Intelligence.
Details on these transactions and more in the full articles: Wu Blockchain News | Arkham Intelligence
#Bybit#ETH#USDT#GalaxyDigital#FalconX#CryptoHack#NorthKorea#ARKham#Blockchain#VC#Crypto#Security#Hacking#DigitalAssets#Fintech#Cryptocurrency#BlockchainAnalysis#MarketTrends#TechNews
🚀 Crypto Analyst Manya Releases Research Tool Rankings
Crypto analyst manya has released a ranking of personal research tools. According to ChainCatcher, the rankings categorize tools into different levels based on their effectiveness. The S-tier includes Dune and frontrun.pro, while the A-tier features Coinglass, RootData, Drop, MetaSleuth, and DefiLlama. B-tier tools comprise Arkham, Bubblemaps, Dexscreener, Surf, Nansen, and CoinMarketCap. C-tier tools include Cryptorank and others.
#CryptoAnalyst#ResearchTools#CryptoRanking#Dune#frontrunpro#Coinglass#RootData#Drop#MetaSleuth#DefiLlama#Arkham#Bubblemaps#Dexscreener#Surf#Nansen#CoinMarketCap#Cryptorank