Можно ли в 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
🇺🇸California Outlines Core Principles for Frontier AI Governance
California has released a landmark report on frontier AI policy, laying out foundational principles for responsible governance. The document emphasizes evidence-based policymaking, calling for regulatory interventions that weigh both risks and societal benefits of advanced AI. Transparency, accountability, and empirical rigor are central themes — with recommendations including whistleblower protections, third-party audits, and systems for adverse event reporting.
Of particular note is the focus on early policy design: choices made today will shape the future direction of AI innovation and regulation. California positions itself not just as a tech hub, but as a model for how democratic systems can proactively govern powerful emerging technologies.
#AIRegulation
📖Who Speaks for the AI Generation?
A new report from The Alan Turing Institute reveals a critical omission in AI policymaking: children’s voices. Despite being among the most affected by the long-term impacts of AI systems, children remain largely excluded from regulatory and governance discussions shaping their digital futures.
The report urges policymakers to actively include children's experiences and perspectives in the design and oversight of AI systems. It calls for frameworks that move beyond abstract protections and toward direct engagement with younger users—those who will live longest under the consequences of today's AI decisions.
#AI#AIRegulation
🇺🇸California’s AI Legal Advisory: A Blueprint for Accountability
California has issued two detailed legal advisories on artificial intelligence, marking a significant step toward regulating AI under state law (📥here and here). These advisories outline specific AI-related practices that could be deemed unlawful, offering clarity on deceptive and harmful uses of AI while reinforcing consumer protections.
Key takeaways:
✔️ Misrepresenting the capabilities of AI systems is explicitly called out. For instance, falsely advertising an AI's accuracy, claiming human involvement when it's AI-driven (or vice versa), or asserting bias-free operation without evidence is now under scrutiny.
✔️ Practices like deepfake creation, voice cloning, or media generated by AI without proper disclosure may be considered deceptive. Similarly, impersonation—whether for fraud, harm, or government duties—is a clear violation.
✔️ AI applications with unfair, unethical, or oppressive consequences, even if unintentional, could also face legal challenges under the state’s laws.
Notably, California’s new AI laws, effective January 1, 2025, address business disclosure requirements, unauthorized use of likeness, and AI in election campaigns, among others. These developments reflect a growing demand for transparency and ethical boundaries in AI deployment.
#AIRegulation#AI
Европейская комиссия опубликовала ответы на важнейшие вопросы по Закону об искусственном интеллекте
Европейская комиссия представила ответы на важнейшие вопросы о Законе ЕС об искусственном интеллекте - от систем искусственного интеллекта с высоким уровнем риска до защиты прав.
#EUAIAct#AIRegulation
🌐AI and Democratic Values: 2025 Report Released
The Center for AI and Digital Policy (CAIDP) has published the latest edition of the AI and Democratic Values Index (AIDV 2025) — a global benchmark for AI governance. Covering AI policies in 80 countries, the 1,500-page report tracks national progress, highlights trends, and provides a comparative analysis of AI strategies worldwide.
This year, Canada, Japan, Korea, the Netherlands, and the UK lead the rankings, demonstrating strong commitments to ethical AI and democratic accountability. The AIDV Index, now in its fifth edition, is built on contributions from 1,000+ experts across 120 countries.
#AIRegulation#AIGovernance
🌐UN Urged to Set Global AI "Red Lines" Before It’s Too Late
Over 200 experts, including 10 Nobel Prize winners, have signed an open letter calling on the United Nations to establish and enforce global “red lines” for artificial intelligence by the end of 2026. The letter warns that advanced AI systems already show signs of deceptive and harmful behavior while being granted increasing autonomy, creating risks ranging from engineered pandemics and mass disinformation to threats against national security and human rights.
The group demands explicit bans on AI applications such as direct control of nuclear weapons, mass surveillance, and impersonation of humans without disclosure. Among the signatories are AI pioneers Geoffrey Hinton and Yoshua Bengio, OpenAI co-founder Wojciech Zaremba, and leaders from Anthropic and Google DeepMind. The call cites precedents like the 1987 Montreal Protocol as proof that global cooperation can work — but warns that time to act is rapidly running out.
#AIEthics#AIRegulation
🤖🇺🇸TRUMP WEIGHS AI EXECUTIVE ORDER — MANDATORY GOVERNMENT VETTING
🔹 Draft order would require federal approval before releasing AI models citing Anthropic "Mythos" cybersecurity risks 🛡️
🔹 Tech companies face potential 90-day review delays and up to $50M penalties for unauthorized deployment 💰
🔹 Silicon Valley leaders pushing back claiming this would "kill American AI innovation" vs China competition 🇨🇳
🔹 Comes after Iranian hackers used AI tools to target US infrastructure in latest cyber escalation 🎯
Biden had AI guidelines — Trump wants AI guardrails with real teeth and enforcement power 🦷⚡
#AIRegulation#TechPolicy#CyberSecurity
@america
🚨🤖TRUMP AI CRACKDOWN — Silicon Valley vs Federal Government!
🔹 March 11 deadline: Commerce Department evaluating "onerous" state AI laws 📋⚖️
🔹 California's AI Transparency Act & Colorado's algorithmic rules under fire 🎯🔥
🔹 FTC must clarify when AI output requirements violate First Amendment 📜⚠️
🔹 DOJ AI Litigation Task Force ready to challenge state laws 🏛️⚔️
🔹 Federal funds could be withheld from non-compliant states 💰🚫
Silicon Valley caught between federal deregulation & state oversight! Biggest tech vs government showdown since antitrust! 💥
#AIRegulation#TechPolicy#SiliconValley
@america
🇪🇺Europe's Industrial Leaders Call for a Pause on the AI Act
A coalition of 46 CEOs from Europe’s most influential companies (including Airbus, ASML, TotalEnergies, Lufthansa, and Mistral) has formally asked the EU to halt the implementation of the AI Act for two years. In an open letter, they argue that the upcoming obligations, particularly for general-purpose and high-risk AI systems, are marred by regulatory ambiguity and administrative overlap. These burdens, they warn, are jeopardizing Europe’s innovation capacity and global competitiveness.
The appeal lands amid ongoing debate in Brussels over how to balance economic growth with digital regulation. EU Commissioner Henna Virkkunen has stated she will consider a “clock-stop” if implementation standards are not finalized by August. .
#AIAct#AIRegulation
🇪🇺EU Releases Guidelines on Prohibited AI Practices
The European Commission has published a 140-page guide on AI practices prohibited under the EU AI Act. These guidelines outline AI applications considered "unacceptable" due to risks to fundamental rights and European values.
While non-binding, these guidelines provide legal analysis and practical examples to help stakeholders navigate compliance. The final interpretation will rest with the Court of Justice of the EU (CJEU). The Commission has approved the draft, but formal adoption is still pending.
#AIRegulation#AIAct