TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 6 слични објави

Пребарај: #cryptopolicy

当前筛选 #cryptopolicy清除筛选
Venture Village Wall 🦄

@venturevillagewall · Post #4330 · 07.03.2025 г., 13:00

U.S. Must Lead in Crypto Regulation U.S. Treasury Secretary Bessent emphasizes the need for the U.S. to take a global lead on cryptocurrency. Key points include bringing Bitcoin transactions onshore and ceasing government Bitcoin sales. Notably, the evolving regulatory landscape also aims to foster greater adoption of cryptocurrencies in the U.S. #Crypto#U.S. #Bitcoin#Regulation#SEC#BTC#Blockchain#Innovation#CryptoAdoption#Finance#Bessent#Investment#CryptoPolicy#DigitalAssets#Mainstream#MarketTrends#Tech

Crypto M - Crypto News

@CryptoM · Post #65242 · 12.04.2026 г., 08:25

🚀 Former Bank of China VP Comments on U.S. Crypto Regulation Approach Former Bank of China Vice President Wang Yongli has expressed that the United States' method of classifying and regulating crypto assets warrants examination. According to NS3.AI, Wang Yongli noted that the CLARITY Act guidance document represents a notable advancement. However, he emphasized that nations should tailor their crypto asset regulations to align with their specific circumstances. #BankOfChina#CryptoRegulation#USCrypto#CLARITYAct#WangYongli#CryptoPolicy#FinancialRegulation#Blockchain

Crypto M - Crypto News

@CryptoM · Post #65060 · 10.04.2026 г., 17:27

🚀 Senator Lummis Urges Congress to Pass CLARITY Crypto Bill Before 2030 Senator Cynthia Lummis has called on Congress to expedite the passage of the CLARITY crypto market structure bill, emphasizing its importance as a critical legislative opportunity before 2030. According to NS3.AI, Lummis highlighted the urgency of the situation, framing the bill as a narrowing legislative window rather than a finalized policy measure. Her statement underscores the need for timely action to establish a clear regulatory framework for the cryptocurrency market. #SenatorLummis#CLARITYBill#CryptoRegulation#Cryptocurrency#Congress#Legislation#Blockchain#CryptoPolicy#RegulatoryFramework#CryptoNews

Crypto M - Crypto News

@CryptoM · Post #64785 · 09.04.2026 г., 23:37

🚀 South Korea Implements New Rules for Managing Public-Sector Virtual Assets South Korea has approved a plan to manage 78 billion won, equivalent to approximately $57.7 million, in public-sector virtual assets. According to NS3.AI, the new regulations mandate that any seized or confiscated cryptocurrency from personal wallets must be promptly transferred to an institutional cold wallet, which is not connected to the internet. Additionally, the rules stipulate that private keys and recovery phrases must be controlled by at least two individuals through a split-access arrangement. #SouthKorea#PublicSector#VirtualAssets#Cryptocurrency#Regulations#DigitalAssets#CryptoSecurity#ColdWallet#Blockchain#CryptoPolicy

Venture Village Wall 🦄

@venturevillagewall · Post #4289 · 02.03.2025 г., 19:01

Bitcoin Surges Following Large Whale Activity A Hyperliquid whale profited over $10M after opening positions shortly before the Bitcoin price surge to $90,000. Meanwhile, Donald Trump proposed a U.S. national crypto reserve including XRP, SOL, and ADA, raising concerns about insider trading due to the choice of assets. More details on these developments can be found here: Leviathan News and Wu Blockchain News. #Bitcoin#Crypto#XRP#SOL#ADA#Trump#Whale#Profit#NationalReserve#InsiderTrading#Blockchain#Finance#Investing#MarketTrends#BlockchainNews#CryptoPolicy#DigitalAssets#Fintech#VC#AI

Crypto M - Crypto News

@CryptoM · Post #64854 · 10.04.2026 г., 04:34

🚀 South Korea Proposes Stricter Crypto Transfer Regulations South Korea's Financial Intelligence Unit is set to implement more stringent rules on cryptocurrency transfers. According to NS3.AI, the new regulations will mandate reports on suspicious transactions for low-risk transfers exceeding 10 million won, particularly involving private wallets and overseas exchanges. These low-risk transfers will only be permitted if the sender and receiver are verified as the same individual. Additionally, high-risk transactions will face further restrictions. #SouthKorea#CryptoRegulations#Cryptocurrency#FinancialRegulations#Blockchain#CryptoTransfers#DigitalCurrency#FinTech#CryptoCompliance#CryptoPolicy