Можно ли в 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
💳💸 O‘zbekistonda Google Pay va Apple Pay ishga tushishi mumkin!
🇺🇿 Prezident Shavkat MirziyoyevAQShning yirik kompaniyalari, investitsiya fondlari va moliya institutlari vakillari bilan uchrashuvda ushbu to‘lov tizimlarini mamlakatimizda joriy etish masalasini muhokama qildi.
💳 Agar bu qaror qabul qilinsa, O‘zbekiston foydalanuvchilari uchun xalqaro raqamli to‘lovlar yanada qulay va tezkor bo‘ladi.
➡️#applepay#googlepay | Birinchi raqamli IT-Blog
💸Top Fintech Apps Worldwide for October 2019 by Downloads
#GooglePay (Tez) was the most downloaded fintech app worldwide for October 2019 with close to 17 million installs, which represented a 24% increase from October 2018. The country with the most installs of the app during this period was India🇮🇳 at 99% of its total downloads.
#PhonePe was the second most installed fintech app worldwide last month with close to six million installs, which represented a 23% increase from October 2018. The country with the largest number of PhonePe installs was also India🇮🇳 at 99%.
🎁 Download Cash App using this link or this code WFSDXPP and get a £5 reward!
🦅@PerspectiveIX via SensorTower.
🤝Support PerspectiveIX.
☕️Starbucks’s mobile payments system is so popular than Apple’s or Google’s in🇺🇸
By the end of this year, a quarter of U.S. smartphone users — 55 million people — over the age of 14 will make an in-store mobile payment. More than 40 percent of those people will have done so through Starbucks’s mobile payments app, according to new data from research firm eMarketer.
The Starbucks app, which launched before the other three top payments apps — #ApplePay, #GooglePay and #SamsungPay — has long been the most successful payments app. It’s likely going to maintain that lead over the next few years.
🚀@PerspectiveIX
📖 Read more at t.me/iXNews/25746
💸Leading Payment Methods Used in 2018
A credit card stored automatically on a computer is the main form of online payment in the U.S, according to a survey on Mobile Banking conducted by Ipsos and ING. #Paypal came in second place with about 1 in 5 respondents citing the online payment as their preferred form of online payment.
#AmazonPay, #GooglePay, and #ApplePay were some of the less common forms of online payment for respondents interviewed by Ipsos and ING.
🚀@PerspectiveIX via Statista.
💳 Tonhub non-custodial wallet launched a Visa debit card
Tonhub has launched a Visa debit card, allowing users to make payments directly from their $TON or $USDT balances. Available for European ID holders, the card offers minimal fees (1.5% per transaction) and supports global payments, including SEPA, SWIFT, Apple Pay, and Google Pay.
Tonhub plans to expand access to CIS, Latin America, and the Middle East by 2025 and integrate with wallets like TrustWallet. With accounts managed via smart contracts on the TON blockchain, users retain full control over their funds.
Learn more at Tonhub’s website.
#TON#SWIFT#ApplePay#Web3#GooglePay#Tonhub#USDT
🚀 Binance to Introduce USDS Across Multiple Services
According to the announcement from Binance, the platform is set to integrate USDS (USDS) into several of its services, including Binance Simple Earn, "Buy Crypto," Binance Convert, Binance Margin, and VIP Loan. The rollout is scheduled to commence on 2026-04-09 at 08:00 (UTC), when USDS Flexible Products and Locked Products will be available for subscription on Binance Simple Earn.
In addition to the Simple Earn integration, users will have the option to purchase USDS using VISA, MasterCard, Google Pay, and Apple Pay, or trade it with their account balances on the "Buy Crypto" page. This feature will be accessible within one hour of USDS being listed on Binance Spot. Furthermore, Binance Convert will allow users to trade USDS against BTC, USDT, and other tokens without incurring any fees, also within one hour of its listing.
For those interested in margin trading, Binance Margin will introduce USDS as a new borrowable asset on both Cross and Isolated Margin. The trading pairs USDS/USDT, BTC/USDS, and ETH/USDS will be available on Cross Margin starting at 2026-04-09 08:00 (UTC). Similarly, these pairs will be accessible on Portfolio Margin at the same time. Additionally, USDS will be listed as a borrowable coin on VIP Loan shortly after its spot listing.
Binance advises users to exercise caution, as newly listed tokens can exhibit significant volatility. It is recommended that traders implement robust risk management strategies. For the latest information on marginable assets, users are encouraged to consult the Margin Data section. This integration marks a significant expansion of USDS's availability across Binance's diverse range of financial services.
#Binance#USDS#BinanceSimpleEarn#BuyCrypto#BinanceConvert#BinanceMargin#VIPLoan#CryptoTrading#MarginTrading#SpotListing#BTC#ETH#USDT#CrossMargin#IsolatedMargin#PortfolioMargin#VISA#MasterCard#GooglePay#ApplePay#RiskManagement#CryptoVolatility#FinancialServices#CryptoAssets