Можно ли в 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
⚡️ SEC is changing the rules of the game
At the OECD roundtable, #SEC head Paul Atkins presented a new strategy - Project Crypto
🟡 Onchain capital raising without endless legal barriers
🟡 Allowing the format of "super apps" for trading (trading, staking, lending in one place)
🟡 Most tokens will not be considered securities
🟡 Abandoning "regulation by coercion" in favor of clear and predictable rules
🟡 Emphasizing international cooperation (references to MiCA in Europe)
⚡️⚡️⚡️Unexpected from #SEC: Spot Ethereum ETFs are about to be approved
Exchanges wishing to trade cellular Ethereum ETFs have received an urgent request from the SEC to update Forms 19 b4, Coindesk reports. This may indicate possible approval of applications by Thursday.
However, according to Coindesk, S1 applications also need to be approved to start trading, and SC can consider them indefinitely. One company that spoke with the SEC noted an improvement in the approval process, although it previously believed that the regulator was delaying the deadline.
👌Bloomberg analysts have increased the probability of approval of the spot Ethereum ETF from 25% to 75%. A decision on VanEck is expected on May 23.
Before approving the spot Bitcoin ETF, the regulator asked the exchanges to take similar actions.
SEC Issues alert on Pump and Dump Memecoins
🥳
The #SEC warns investors about fraudulent "pump and dump" memecoins created by celebrities.
📈Sign up on Bybit to trade with me
🇺🇸 American banks have applied to the #SEC for permission to store #Bitcoin
The ability for banks to store $BTC will immediately allow them to start selling their banking products to all consumers — which in turn can lead to a significant increase in demand 🚀
#SEC backs down — tokens have never been securities 😅
The SEC stated that it had never directly referred to tokens as securities. This follows from a footnote to the regulator's lawsuit against the #Binance exchange.
By using the term "crypto asset securities", the Commission does NOT mean a token as such, but a complete set of contracts, expectations and agreements.
The regulator "regrets" any confusion that may have arisen in connection with this and undertakes not to use it anymore.
The $UNI price plummeted by ~16% (7H) after #SEC warned to sue @Uniswap.
Watch out for a possible further price drop as Smart trader 0x335 just deposited 1.25M $UNI ($12.05M) to #Binance at ~$9.66 via 2 wallets in the past hour, realizing an estimated profit of $4.23M (+54.7%)!
Notably, the whale also made $5.76M in total profit from $ETH, $COMP, and $AAVE before.
Follow @spotonchain and set alerts for $UNI at https://platform.spotonchain.com/en/platform/token?name=UNI
💰 .The trial with Ripple has been completed
Ripple (XRP) was fined $125 million for institutional token sales.
The #XRP token itself is not recognized as a security, which means that all claims from the #SEC have been settled.
The four-year-long story has come to an end.
The #SEC's powers are being reduced 😱
A post for those who like to figure it out 🔩
Yesterday, the US Supreme Court limited the SEC's right to hear cases by "full-time judges" (the procedure has been used for cases of securities fraud and financial penalties since the 2008 crisis). The restriction was introduced by 6 votes to 3, there are dissenters.
☝️ Now, in order to consider the case, the SEC must necessarily apply to the federal courts of first instance with the participation of a jury.
❓Why is this important for the crypt?
Some cases "against cryptocurrencies" were considered by the SEC in a "simplified manner," including "incorrect indication of the fund's assets."
Potentially, this restriction will also apply to the definition of assets in the #ETF for cryptocurrency. After all, the SEC believes that a cryptocurrency ETF is an ETF for securities, while the cryptocurrency itself is a commodity/property.
Look at how everything turned around in this election race! The presidents, in pursuit of the votes of the cryptans, are now gradually beginning to put sticks in the wheels of the regulator - the SEC.
Either this is a "circus with horses", or we are really close to masadopshn as never before…
🔹#SEC closes investigation against #Ethereum
The regulator will no longer bring charges, claiming that the sales of #ETH are securities transactions.
This news gave rise to the crypt.
#BTC made a potential retest back to the Major Support zone as expected. Well, this was due to a Positive tweet from Official X account of #SEC on #ETF. This was a fake news as it dropped when came into highlight. Also, mostly event aligns with Technical most of the time. Now today we've to wait and watch for the news to kick in momentum into the market.
By Crypto Australia