今日已更新 302 条资讯 | 累计 41076 条内容
关于我们

标签:#dev

找到 4754 篇相关文章

AI 资讯

Running Coding Agents in Parallel with Git Worktrees

I kept hitting the same wall with coding agents. One Claude Code or Codex session in a repo works great. The moment I wanted two tasks moving at once - login in one terminal, payments in another - they started stepping on each other. Same working directory, same checked-out branch, two processes editing the same files. Chaos. The fix turned out to be a Git feature that has been sitting there for years: git worktree . It gives you several working directories backed by the same repository . Each folder has its own checked-out branch, but all of them share the same objects, commits and branch list. The setup From your main checkout: git worktree add ../integration -b integration main git worktree add ../feature-login -b feature/login main git worktree add ../feature-payments -b feature/payments main Which leaves you with something like: project/ ├── main/ → branch main ├── integration/ → branch integration ├── feature-login/ → branch feature/login └── feature-payments/ → branch feature/payments Now every agent gets its own folder. One terminal per worktree, one agent per terminal, and nobody touches anybody else's files: cd feature-login # agent 1 works here cd feature-payments # agent 2 works here, at the same time The part that surprised me: no push, no pull My first instinct was: agent finishes login, pushes the branch, then I pull it into integration. That's the muscle memory from working in a team. It's unnecessary here. All the worktrees belong to the same repository on the same machine, so Git already knows every branch locally. When agent 1 finishes: cd feature-login git add . git commit -m "feat: implement login" ...the integration worktree can merge it directly: cd ../integration git merge feature/login git merge feature/payments npm test No git push , no git pull . The directories are different, but feature/login and integration are branches of the same repo. When integration is green: cd ../main git merge integration You don't even have to wait for a worktr

2026-08-31 原文 →
开源项目

I love gaming and past few months I’ve been working on a laravel project 😇 for gamers a social network designed for gamers to share , discuss and discover gaming related content would love feedback and honest opinions so far https://norespawn.space

NoRespawn — Gaming Community Forum Join No Respawn — a community built for gamers to share their best clips, swap strategies, get help, discover new tricks, and talk about the games they love across every genre. norespawn.space

2026-08-31 原文 →
AI 资讯

When HTTP Retries Become Dangerous: Idempotency in Symfony Without the Fairy Tales

Retries are one of those things that look harmless until the first time they duplicate a real business operation. A request times out, so the client retries it. Reasonable. But what if the first request actually reached the server? What if the application already created the order, reserved the stock, sent the message, or called a payment provider — and only the response was lost? From the client's point of view, the request failed. From the application's point of view, it may already be finished. Send the same request again and you can get the worst kind of bug: one that is technically understandable, difficult to reproduce, and very expensive in production. This is the problem that pushed me to build HttpIdempotencyBundle , a small Symfony bundle for explicit HTTP request idempotency. But the interesting part is not the bundle itself. The interesting part is everything that has to be true before we can safely say: "This request is a retry of the same operation, so we should not execute it again." And just as importantly, what we cannot guarantee. A timeout does not mean the operation failed Consider a simple endpoint: #[Route('/orders', methods: ['POST'])] public function createOrder (): JsonResponse { $order = $this -> orderService -> create (); return new JsonResponse ([ 'id' => $order -> getId (), ], 201 ); } Now imagine this sequence: Client -> POST /orders Server -> creates order #742 Server -> sends 201 response Network -> connection dies Client -> sees timeout Client -> retries POST /orders Nothing unusual happened. The client did exactly what clients often do after a timeout. The server did exactly what it was asked to do. And yet, unless we have another mechanism in place, we may now create order #743 as well. The key idea is simple: transport failure and business-operation failure are not the same thing. HTTP cannot always tell the client whether the operation happened. Give the operation an identity A common solution is an Idempotency-Key . The client g

2026-08-31 原文 →
AI 资讯

Adam and AdamW: The Optimizer That Made Modern LLM Training Possible

Hello, I'm Shrijith Venkatramana, and I'm building LiveReview — a blast-radius aware AI code review built for your business-critical systems. Star us to help devs discover the project, give it a try, and share your feedback to help improve the product. Most people learn neural networks by staring at the model. Weights. Attention. MLPs. LayerNorm. Tokenizers. Context windows. But when you actually train an LLM, there is another piece of machinery making billions of decisions every second: the optimizer. A 70-billion-parameter model does not "learn" because gradient descent tells it which direction is better. It learns because an optimizer turns an enormous, noisy stream of gradients into parameter updates that are small enough not to explode, large enough to make progress, and adaptive enough that different parameters can move at radically different effective rates. For the last decade, the dominant answer has largely been some form of Adam , and increasingly AdamW . The interesting part is that Adam is not some mysterious LLM-specific invention. The original Adam paper was submitted in December 2014 by Diederik Kingma and Jimmy Ba, before the Transformer, before GPT, and before the modern LLM era. Kingma was working on scalable machine learning and generative models; Ba was then a PhD student working with Geoffrey Hinton at Toronto. Three years later, the Transformer paper used Adam directly in its training recipe. Then came AdamW, which fixed a subtle but important problem in how regularization interacted with adaptive optimization. By 2025, Adam was sufficiently influential to receive an ICLR Test of Time award. So what exactly is Adam doing? And why is AdamW usually what you actually want when training a Transformer? 1. First, forget Adam: what problem is the optimizer solving? Suppose your neural network has parameters theta = [theta_1, theta_2, ..., theta_N] and your training batch produces a loss L . Backpropagation gives you g = dL/dtheta The simplest possibl

2026-08-31 原文 →
AI 资讯

Time‑Based Public Access for the `/tv` Route in a Next.js App

Time‑Based Public Access for the /tv Route in a Next.js App TL;DR: I added a temporal gate that lets anyone hit /tv without a session cookie between 9 am‑6 pm America/Cancun. Outside that window the request falls back to the normal auth middleware. The change lives in src/lib/auth.ts and src/middleware.ts and required proper timezone handling and a tiny refactor of the auth flow. The Problem Our TV dashboard ( /tv ) is meant to be displayed on a wall screen in the office lobby. The screen should be visible to anyone during office hours, but it must stay protected after hours. The original middleware ( src/middleware.ts ) forced a session cookie ( AUTH_COOKIE_NAME ) on all routes, including /tv . The result was a “401 Unauthorized” on the lobby screen after 6 pm, which broke the intended user experience. The symptom was simple: GET /tv → 401 Unauthorized The error came from the auth middleware that blindly redirected unauthenticated requests to the login page. We needed a conditional bypass that only applied to the /tv path and only during the defined business hours. What I Tried First My first instinct was to add a quick if (request.nextUrl.pathname === "/tv") return NextResponse.next(); at the top of the middleware. That let the request pass, but it also opened the route for the whole day, ignoring the time constraint. I tried to read the server’s local time ( new Date() ) and compare the hour, but the server runs on UTC, so the check was off by 5 hours for the America/Cancun zone. The result was that the route was either always open or always closed, depending on where the CI runner was located. I also considered using a third‑party library like moment-timezone , but pulling in a heavy dependency for a single hour check felt overkill. The Implementation 1. Add a tiny time‑window helper I created a pure function isWithin in src/lib/auth.ts . It receives a start hour, an end hour, and a timezone identifier, then returns a boolean indicating whether the current momen

2026-08-31 原文 →
开发者

I Built a Free Tool That Turns Your GitHub Profile Into a Shareable Stat Card — Here's How

The Problem GitHub profiles are data-rich but visually boring Developers want to "flex" their stats but have no aesthetic way to do it The Solution DevCard: enter username → pick theme → download PNG Show all 3 themes with screenshots How It Works (Architecture) Cloudflare Worker + GitHub GraphQL API (single query) Edge caching strategy Client-side rendering with html-to-image The CORS avatar trick (base64 conversion) The RPG Class System (fun section) How top language maps to character class Full class table (TypeScript → Archmage, Rust → Forgemaster, etc.) This section alone will get shares Try It Yourself Link: https://www.devcard.tech/ CTA: "Drop your card in the comments" What's Next VS Mode (compare two devs) More themes Open to suggestions

2026-08-30 原文 →
AI 资讯

How to setup WikiEduDashboard for OSS contribution

1. Problem Statement I wanted to contribute to an open source project called WikiEduDashboard , a web application built by Wiki Education. It helps instructors and program leaders run Wikipedia-editing classes and campaigns: students join a course, make edits to Wikipedia, and the dashboard tracks their work. To contribute code to this project, I first need a working copy of it running on my own PC. This is called a "local development environment." Without it, I can't test any changes I make before sending them back to the project. The problem: this project was built with tools that work best on Mac or Linux, not on plain Windows. So the first challenge wasn't even the project itself, it was figuring out how to run a Linux-friendly project on a Windows PC. 2. The Solution (High Level) Instead of fighting Windows directly, we used a feature built into Windows called WSL (Windows Subsystem for Linux) . WSL lets a real Linux system (Ubuntu, in our case) run inside Windows, side by side with your normal Windows apps. It's not a separate computer or a virtual machine you have to babysit, it just works like an extra terminal environment on the same PC. Once inside Ubuntu, we could follow the project's official setup instructions exactly as written, since those instructions assume a Mac or Linux machine. The overall plan looked like this: Get a Linux environment running on Windows (WSL + Ubuntu) Get a personal copy of the project's code (fork it on GitHub, then clone it) Install the programming language the project is built with (Ruby) Run the project's automated setup script, which installs the rest of the required tools (database, background job system, etc.) Start the actual application and view it in a browser Build the frontend (the visual, interactive part of the site) Set up an editor (VS Code) that can actually see and edit the code living inside Ubuntu 3. Step by Step: What We Did and Why Step 1: Install WSL and Ubuntu What: WSL is a Windows feature that runs a re

2026-08-30 原文 →
AI 资讯

The Need for a Modern UML and Diagram Engine (Part 1)

How It Started I am a backend software engineer, primarily working in the Java ecosystem. Most developers in my space know about PlantUML and have probably been using it for years—I certainly have. PlantUML has long been a go-to tool for developers who need a robust way to write UML diagrams as code. But let's face it: PlantUML is showing its age. As powerful as it is, PlantUML can feel slow, its default look-and-feel is dated, and its interactive feature set has lagged behind modern development workflows. That is a major reason why alternatives have gained so much ground. Tools like Draw.io and Mermaid.js have steadily captured a large portion of the mindshare that PlantUML once held. While Draw.io is a visual drag-and-drop tool rather than a pure text DSL, it offers rich component sets and high customizability. However, text-based versioning and quick code playback aren't its primary strengths. On the other hand, Mermaid.js brought text-to-diagramming into the modern web. It is fast, renders across browsers and IDEs, offers an accessible DSL, and integrates directly into platforms like GitHub and Notion. Yet, I felt we could take this concept even further. We need something more modern, more customizable, and more tactile—a text-to-diagram engine that is fast, easy to learn, and visually sharp, while bridging the gap between raw code and visual canvas control. Introducing DrakoFlow For a long time, I’ve dreamed of having a diagram engine that makes sharing architecture effortless. A tool that enhances the documentation experience rather than standing in the way of it. So, I finally decided to build it. I wanted DrakoFlow to be fast, robust, and elegant—not only in its syntax, but in its visual output. Most importantly, I wanted it to be 100% free, open-source, and privacy-first (running entirely in the browser with zero server dependencies). Building it was a challenge. As a backend developer, creating a heavily interactive, client-side web application meant stepp

2026-08-30 原文 →
AI 资讯

Live API specs for coding agents

Live API specs for coding agents An agent writing frontend code has to know the backend's API. It has three options. It can read the backend source and work out from scratch what the service already publishes. It can ask you, which promotes you to API documentation. Or it can swallow the entire OpenAPI document in order to use one route out of it. Then it does the same thing again tomorrow, against a stale swagger.json you exported last week. docs-mcpserver takes the spec straight from the running service, caches it, and serves it one operation at a time. The config { "cacheDir" : "./cache" , "libraries" : [ { "name" : "orders-api" , "description" : "Order handling service" , "sources" : [ { "type" : "url" , "origin" : "https://localhost:5001/openapi/v1.json" , "kind" : "schema" , "name" : "orders" } ] } ] } npm install -g docs-mcpserver claude mcp add docs -- docs-mcpserver --config /path/to/dev-docs.json That is the whole setup. One operation, not the whole spec The agent lists the definitions in orders , picks the one it needs, and fetches that. For an OpenAPI document the path operations are exposed as definitions named GET /orders/{id} , so it can also search by keyword. A few hundred tokens for the operation it is writing against, instead of the entire document. That keeps working as the service grows, which a pasted spec does not. The backend does not have to be running Every call is answered from the cached spec, never from the network. The fetch happens on startup and then in the background while you work, so an endpoint you added 20 seconds ago is already visible. Start the backend once, shut it down, and keep building the frontend. The agent still has real routes and real payload shapes. If the service is down, or answers with something that is not a spec, the last known-good copy keeps being served. Code and issues: github.com/jgauffin/dev-docs-mcp . On npm as docs-mcpserver .

2026-08-30 原文 →
AI 资讯

Delta encoding multiplayer game state

Old Light is a browser strategy game where a tab can stay open for days. The client holds a full copy of the galaxy state it is allowed to see, and the server keeps that copy honest by sending patches: every change arrives as a world.delta message the client merges into what it already has. Sending changes instead of resending state is textbook delta encoding. What that leaves open is what a game state patch actually holds, and why the patch a rival receives is not the one you receive. I covered how the stream starts (one snapshot on connect, then deltas) and the time-math traps inside it in the networking post . This post is about the delta itself. What goes in a game state patch When people say delta encoding they usually mean byte diffs: compare two versions of a blob, ship the difference. That requires the sender to know which version the receiver holds. A game server broadcasting to thousands of sockets can't afford that; tracking a per-client "last known state" and diffing against it on every change would be more expensive than the update. So an Old Light delta states facts about players and sectors instead: interface WorldDelta { added ?: { players ?: Player [] }; removed ?: { playerIds ?: string [] }; updated ?: { players ?: Player []; sectors ?: Sector []; dirtySectors ?: SectorCoord []; // map data here went stale, refetch it tradeBoard ?: TradeBoardDelta ; // the market board moved deals ?: DealsDelta ; // a negotiation moved; only its two parties get this }; serverNow : number ; } A delta says a player joined, an id is gone, a player's row changed, or a sector's public map data went stale. The last two fields carry no payload. They say a surface moved, a client with that surface open goes and reads it, which keeps a busy marketplace off every socket that isn't looking at one. The server can emit the identical message to every socket without knowing what any of them currently holds, and the client can apply it to whatever it has. It also tells the rendere

2026-08-30 原文 →
AI 资讯

The Docker Handbook: From Zero to Production-Ready Containers

Docker has become an essential tool for developers, DevOps engineers, and anyone deploying applications today. It solves the age-old problem of “it works on my machine” by packaging an application with everything it needs into a lightweight, isolated unit called a container. This guide takes you from absolute beginner to confidently building and running real‑world applications with Docker. 1. Why Docker Exists (The Problem) Before Docker: “It works on my machine” is the daily mantra 😵 Different OS → different bugs, different dependency versions Onboarding a new developer takes hours (Node, DB, caches, environment variables…) Servers are hand‑configured snowflakes, impossible to reproduce exactly Docker solves this: 👉 It packages your app plus everything it needs into a lightweight, isolated unit called a container . That container runs identically everywhere : Your laptop A teammate’s machine A CI/CD pipeline A production server in the cloud 2. What is Docker? Docker is a platform that lets you: Define application environments as code ( Dockerfile ) Build images from those definitions Run containers from those images Share images via a public registry ( Docker Hub ) Simple analogy: Docker = Lunch box 🍱 Your app + dependencies = the food inside Container = the sealed box you can carry anywhere, and when you open it the meal is exactly the same 3. Key Concepts (Must Know First) 📦 Image A blueprint of your application environment. It contains the OS files, dependencies, code, and configuration needed to run your app. Example images: node:18-alpine – Node.js on a tiny Alpine Linux postgres:15 – PostgreSQL database server nginx – a fast web server Think: “Class in OOP” 🚀 Container A running instance of an image . You can have multiple containers from the same image, each isolated from the others. Think: “Object created from a class” 🧱 Dockerfile A text file that defines how to build an image . It lists step‑by‑step instructions, like a recipe. Example: FROM node:18 WORKD

2026-08-30 原文 →
开发者

RightRead - finally a replacement for Mozilla Pocket

Been looking for a simple, offline ready web application to save things I want to read after Pocket shut down. Couldnt find anything that I liked so created one - hopefully others might like. monkeydust / rightread Read-later: capture links from anywhere, read them clean and offline rightread Capture links from anywhere. Read them clean, later, offline. Paste a link. It gets extracted and it's ready to read, clean and offline. Save a link from your phone's share sheet or your browser toolbar. rightread strips the page down to the article, with no ads, no cookie banners and no newsletter popups, and keeps it readable offline in typography built for long reading. Why this exists On 22 May 2025, Mozilla announced it was winding Pocket down . I'd used it for years for one thing: saving something on my phone and reading it properly later, usually when I was on the tube. The alternatives were mostly 'meh' so I built the small thing I missed. One queue, clean text, works on a plane, running on a server I control with the whole library in a single SQLite file I can copy. The reading list lives on your… View on GitHub

2026-08-30 原文 →
AI 资讯

Help Wanted: Validate a React Flex Forms Sample in SharePoint Online

I’m looking for a little community help validating a new SharePoint Framework sample: React Flex Forms . What does it do? The sample contains two SPFx web parts: Form Designer — creates and manages one-page form definitions using supported SharePoint field types. Form Renderer — loads a published form, validates responses, and saves submissions to a SharePoint list. The sample includes automated tests and the local lint, build, and packaging checks are passing. The remaining gap is real-tenant validation and the static screenshots required for the PnP sample README. Could you help? If you have access to a SharePoint Online tenant and a few minutes to spare, please try the sample and capture: The Form Designer working in the SharePoint-hosted workbench. The Form Renderer displaying and submitting a published form. Dummy data is completely fine. Please remove or blur tenant, site, list, user, and other sensitive details before sharing. Feedback about provisioning, permissions, validation, submission, keyboard use, responsive behavior, dark theme, or high-contrast mode would also be very valuable. You can attach the scrubbed screenshots and observations directly to PR #6473 . The setup instructions are included in the sample README. This is a small request, but it would significantly speed up the final validation and help move the contribution toward completion. Thank you to anyone who can lend a tenant or share feedback. sharepoint #spfx #opensource #webdev

2026-08-30 原文 →
AI 资讯

Building a Vedic Astrology API: thread-local bugs, 1,500-year-old test fixtures, and a 429 disguised as CORS

Astrology apps are one of India's quietest huge markets — panchang widgets, kundli generators, matrimonial matching, muhurta pickers. Under every one of them sits the same unforgiving requirement: the astronomy has to be exactly right , because your user's grandmother has a printed panchang on her wall and she will check. I spent the last few months building GrahaAPI — 237 REST endpoints across 23 modules of Vedic astrology, Hindi + English in every response. This post isn't a feature tour. It's the four engineering problems I didn't expect, because I think they're interesting even if you never touch astrology. First, 60 seconds of domain: what the computer actually calculates Strip away the mysticism and Vedic astrology is a coordinate system plus 1,500 years of lookup tables: Tithi (the "lunar date"): the Moon-Sun angular separation, divided into 12° slices. 30 per lunar month. Nakshatra : which of 27 equal 13°20′ segments of the ecliptic the Moon occupies. Dasha : a 120-year planetary period cycle, seeded entirely by the Moon's exact position at birth — a birth-time error of minutes shifts period boundaries by months . The whole thing runs on the sidereal zodiac, offset from the tropical zodiac by ~24° (the ayanamsa — we use Lahiri, the Indian government standard). So: an ephemeris gives you planetary longitudes, and everything else is careful classical bookkeeping. Which brings me to the first bug. Bug #1: the thread-local zodiac Our ephemeris core is a C library with Python bindings, and it holds "which zodiac mode are you in" as global state — per thread . FastAPI runs sync endpoints on a threadpool. First request warms up thread A: sidereal mode set, positions correct. Then a request lands on freshly-spawned thread B: mode silently defaults to tropical , every longitude comes back ~24° off, and — because 24° is almost exactly one nakshatra-and-a-bit — the Moon lands in a plausible but wrong nakshatra. Which seeds the dasha. Which means the API happily returne

2026-08-30 原文 →
AI 资讯

Vincent 0.7.0: The control plane now runs its own development

I just released Vincent 0.7.0 , and this release marks an important milestone for the project: Vincent now builds Vincent. All development on the project now goes through Vincent workflows — from creating an approved GitHub issue through planning, implementation, verification, human gates, merge, and release preparation. The journey from 0.4.0 to 0.7.0 added quite a bit. Workflows became real interfaces Workflows can declare their expected inputs, including: labels types required fields RE2 validation Vincent also gained a workflow-authoring skill designed around a principle I care about quite a lot: don't use an AI agent when deterministic automation can do the job better. Commands and native control flow come first. Agents are used where reasoning is actually required. Recovery became part of the workflow Real automation fails. So Vincent now has mechanisms for continuing rather than throwing work away: follow-ups on completed tasks recorded repair agents for blocked tasks retry backoff safer daemon backup/restore improved diagnostics through vincent doctor The control plane became scriptable 0.7.0 significantly expands the CLI. Tasks can now be started idempotently, created from GitHub issues, populated through JSON/stdin, queried through vincent status , limited with max_cost_usd , and integrated with notifications. Logs, transcripts, approvals, retries, repairs and task answers can all be handled without entering the TUI. The TUI hasn't been neglected either — tasks now open into a dedicated workspace containing steps, attempts, metadata, output and file-grouped diffs. Vincent builds Vincent This is the part I'm most excited about. My own development workflow now uses Vincent itself: GitHub issue ↓ planning ↓ implementation ↓ documentation ↓ cross-platform verification ↓ human gates ↓ merge ↓ release audit Claude Code, Codex or Cursor can provide the inference. Vincent owns the durable workflow, state and verification around them. That's the architecture I've b

2026-08-30 原文 →
AI 资讯

Thin vs Thick Provisioning: Which One Is Actually Eating Your Datastore?

Thin vs Thick Provisioning: Which One Is Actually Eating Your Datastore? You just got an alert: your datastore is at 92% capacity. But when you check the actual VMs, they're barely using half the storage you allocated to them. Welcome to the most common source of confusion in virtualization storage — the gap between allocated and used . This comes down to how you provisioned your virtual disks in the first place. Thin Provisioning: Pay As You Go With thin provisioning, a 100 GB virtual disk doesn't actually consume 100 GB on your datastore right away. It grows as data is written to it. Create ten VMs with 100 GB thin disks, and if they're only using 20 GB each, your datastore shows 200 GB used — not 1 TB. This is why thin provisioning is the default choice for most environments today. It lets you overcommit storage and squeeze more VMs onto the same physical hardware. The catch: you must monitor actual datastore consumption, not just allocated capacity. If every VM suddenly starts writing more data than expected, you can run out of physical space even though your dashboards showed "plenty of room" based on allocated sizes. Thick Provisioning: Reserve It All Up Front Thick provisioning reserves the full disk size the moment you create it. There are two flavors: Lazy-zeroed : space is reserved, but blocks are only zeroed out the first time the VM writes to them. Faster to create, slightly slower on first write. Eager-zeroed : every block is zeroed at creation time. Slower to provision (a 500 GB disk can take a while), but delivers the most predictable, consistent I/O performance from the very first write. Which One Should You Actually Use? A simple rule of thumb: default to thin provisioning for general-purpose VMs — web servers, file servers, domain controllers, dev/test environments. Switch to eager-zeroed thick provisioning specifically for workloads where I/O consistency matters more than storage efficiency — databases, latency-sensitive applications, anything whe

2026-08-30 原文 →
AI 资讯

AWS Open Sources Kiro Crew for Asynchronous Coding Agents

Amazon recently announced Kiro Crew, an open-source system for running multiple Kiro coding agents across sessions, tools, and tasks. The new workspace lets developers assign asynchronous coding tasks to AI agents, allowing work such as incident investigation, ticket triage, migrations, and PR monitoring to continue without active supervision. By Renato Losio

2026-08-30 原文 →
开发者

How to Convert Text to Binary (and Back) in JavaScript

You type "Hi" and the computer stores 01001000 01101001 . Text is just numbers wearing a costume. Here is exactly how a string turns into binary, why UTF-8 matters, and how to do the conversion both ways in a few lines of JavaScript. What "binary" actually means here Computers do not store letters. They store numbers, and every number is a run of ones and zeros. Each character maps to a code point, that number becomes a byte, and each byte is written as eight bits . The letter A has the ASCII code 65. In binary that is: 65 = 01000001 Lowercase a is 97, which is 01100001 . So the whole word "Hi" ( H = 72, i = 105) becomes: 01001000 01101001 Group the bits into bytes of 8 and you can read any binary string back into text. Text to binary in JavaScript The reliable way is TextEncoder . It hands you the raw UTF-8 bytes, so you do not have to worry about character codes above 127. function textToBinary ( text ) { const bytes = new TextEncoder (). encode ( text ); return Array . from ( bytes ) . map ( b => b . toString ( 2 ). padStart ( 8 , " 0 " )) . join ( " " ); } textToBinary ( " Hi " ); // "01001000 01101001" toString(2) gives the binary digits, and padStart(8, "0") keeps every byte a full 8 bits. Without the pad, H would come out as 1001000 (7 bits) and the string would be impossible to split back cleanly. Binary back to text Reverse the process: strip spaces, cut the string into 8-bit chunks, parse each chunk as a base-2 number, then decode the bytes with TextDecoder . function binaryToText ( bin ) { const bits = bin . replace ( / \s +/g , "" ); const bytes = new Uint8Array ( bits . length / 8 ); for ( let i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = parseInt ( bits . slice ( i * 8 , i * 8 + 8 ), 2 ); } return new TextDecoder ( " utf-8 " ). decode ( bytes ); } binaryToText ( " 01001000 01101001 " ); // "Hi" Two checks worth adding in real code: reject anything that is not 0 or 1 , and reject a bit count that is not a multiple of 8. Those two guards catch almo

2026-08-30 原文 →