Можно ли в 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
Bitcoin Exchange Reserve Analysis:
Exchange reserve dropped from 1.9M BTC in 2022 to below 1.1M BTC in 2025.
Inverse correlation with price: as reserve decreases, price increases, peaking at $69.7K.
Indicates long-term holding and bullish sentiment. What's your take on future movements? #Bitcoin#CryptoAnalysis#MarketTrends
📊 Poll Time!
We want to know: What tools do you use to analyze the market? Cast your vote and let us know! #CryptoAnalysis
Vote now here : https://t.ly/2lIs or by replying with the corresponding option number or share your favorite analysis tool in the comments
🔍 Technical Analysis Software
💹 Candlestick Charts
📈 Fundamental Analysis Reports
📊 Market Data Aggregators
#Slex#SlexIO
2 days 23 hours left before the poll closes
Bitcoin Technical Analysis Update 🔝
Hello Crypto Enthusiasts! ⭐️
We're thrilled to announce that Bitcoin has just reached $71,000!
📈This milestone indicates we're on the verge of retesting the All-Time High (ATH) once again.
Current Price Action
✔️Resistance: Primary resistance is at the previous ATH of $72,000. Breaking this could propel Bitcoin higher.
✔️Support: Strong support is at $68,000.
✔️Moving Averages: The 50-day MA is trending upwards at $65,000, and the 200-day MA supports at $60,000.
Technical Indicators
✔️RSI: At 70, indicating bullish sentiment but nearing overbought territory.
✔️MACD: Well above the signal line, confirming a strong bullish trend.
✔️Volume: Increasing, signaling robust market participation.
Positive Predictions
1. Retesting ATH: Bitcoin is poised to challenge and potentially break $72,000.
2. Institutional Interest: Major players are increasing investments.
3. Global Adoption: Increasing adoption by countries and corporations.
4. Technical Upgrades: Upcoming upgrades to improve scalability and efficiency.
5. Bull Market Cycle: Analysts predict potential targets ranging from $80,000 to $100,000 in the coming months.
Conclusion
Bitcoin is buzzing with excitement as we approach new highs. Strong indicators, institutional interest, and global adoption signal a positive outlook. Stay tuned for more updates and prepare for an exhilarating ride to new heights!
Stay Informed
Join our Telegram channel for real-time updates, expert analysis, and to be part of a thriving crypto community. Let's capitalize on the incredible opportunities ahead!
🚀💰📈#Bitcoin#BTC#Crypto#BullMarket#ATH#CryptoAnalysis
⚡️Main news:
🔗Wallet on Telegram enforces new KYC rules, switches provider
🟢 PEPE whale up nearly $5M on investment within a month
💵Next $1 trillion company will be DePIN
📌 Alex Labs rolls out post-exploit recovery plan
💰Bitcoin in 42-day ‘boredom zone’ — traders debate next move
#Cryptoanalysis
#Cryptoenthusiast
#Cryptocurrencies
#Cryptowallet
☄️ZKasino gives investors 72-hour window to get back deposited ETH
💵ZKasino denied it tried to make off with $33 million of investor funds in April and has now opened up a short refund window.
#Cryptoanalysis
#Cryptoenthusiast
#Cryptocurrencies
#Cryptowallet
🚀 Bitcoin's Potential Bear-Market 'Iron Bottom' Predicted by Analyst
A CryptoQuant analyst has projected that Bitcoin might establish a bear-market 'iron bottom' within the $55,000–$60,000 range by the end of 2026. According to NS3.AI, this prediction is grounded in on-chain indicators, notably the MVRV Z-score, which has moderated but remains above negative levels.
#Bitcoin#Crypto#BearMarket#CryptoAnalysis#MVRV#OnChainData#CryptoPredictions#BTC
🚀 Experts Highlight Key Bitcoin Price Levels for Altcoin Bullishness
Bitcoin's price movement is under scrutiny as experts outline critical levels for potential market shifts. According to NS3.AI, Alex Kuptsikevich emphasized that Bitcoin must surpass $75,000 to trigger a bullish trend in altcoins, following multiple unsuccessful attempts to break out of the $70,000–$73,000 range. In a separate analysis, Mike Novogratz noted that Bitcoin needs to establish a stable position at $74,000 to pave the way for a breakthrough beyond $80,000.
#Bitcoin#Altcoins#BullishTrend#MarketShifts#CryptoAnalysis#PriceLevels#BitcoinPrice#Cryptocurrency#BTC