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

Резултати

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

Пребарај: #devblog

当前筛选 #devblog清除筛选
DeckForge Announcement

@deckforge_official · Post #233 · 05.05.2025 г., 08:21

Yama again Last time we talked about what matters to you And today I want to share something that matters to us, developers Soo... 🚂 MEET THE ENGINE 🚂 Choosing an engine for our ambitious game was a challenge DeckForge will eventually be available on many platforms and devices That means that our code has to be easily maintainable, configurable and expandable for different environments We considered several possible solutions, including major game engines We prioritized fast loading, flexibility and cool graphics And after careful evaluation we ended up crafting our own solution on top of the good old three.js library 🤘👵🏻🤘 In terms of rendering - the game is an intricate sandwich of three.js scene wrapped with several layers of html The fun part - three.js is a 3D library with gpu shaders and stuff This enables a lot of visual tools, like VFX and camera shakes Oh, we will make her pretty ✨ Brace yourself, next time i will tell you everything about shaders (👁ˋ _ ˊ 👁) #DeckForge#DevBlog Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements

DeckForge Announcement

@deckforge_official · Post #220 · 20.04.2025 г., 14:08

Hello, future Deck Lords I am Yama - Game Director at DeckForge I represent team LAB behind the development process LAB is a dream team of veterans from different branches of gaming industry and we are very passionate about the game We want to share with you, our players, cool stuff about the development process, listen to your feedback and craft a universe for all of us to enjoy Let's start with some basics 🔵this will be an actual game with gameplay and everything \0/ 🔵we have already produced the alpha version and are moving fast towards beta 🔵multi-platform game, baby! Why are we doing this 🔵we believe the time has come to create a real game product for web3 community 🔵we believe our players want everything a good game should have: gameplay, meta, competitiveness 🔵we believe that we can bring together web3 and web2 communities for their mutual benefit Stay tuned The Forge has just been lit 🔥 #DeckForge#DevBlog Join the DeckForge Community: 🌐YouTube𝕏Twitter 👉Chat👉Announcements

DeckForge Announcement

@deckforge_official · Post #230 · 28.04.2025 г., 14:17

Hello gents Yama here 0/ Let's talk Founder Packs We want you to have fun and profit So we came up with a plan Founder Pack Tiers 🔵 there will be several tiers of Founder Packs (we think 5 is good) 🔵 everyone will be able to claim the lowest tier 🔵 $BOOMS holders - we feel you - depending on your account balance and activity you will be able to claim higher tiers What is inside? 🔵 resources and currency to boost your progress 🔵 powerful items that will give you the edge over competitors 🔵 unique cards and customizations that will not be available through other means 🔵 chance to grab precious NFTs and prizes from our partners Stay tuned for more details #DeckForge#DevBlog#FoundersPack ⸻ Join the DeckForge Community: 🌐YouTube𝕏Twitter 👉Chat👉Announcements