Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Manipulación de bits
Manipulación de bits
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Debates

Guía de Manipulación de bits · 1/6

Concepts

Por ahora, este capítulo solo está disponible en inglés.

Bit manipulation treats an integer as a row of 0s and 1s and reads or changes individual positions directly. The CPU already stores integers in binary, so AND, OR, XOR and shifts usually compile to a single instruction. That makes bit tricks fast and compact, and it lets you express sets of on/off facts in very little code. This chapter covers binary representation, two's complement, the core operators and the vocabulary used in later chapters.

Binary representation

The integer 13 is 1101 in binary. The rightmost position is bit 0, and bit i is worth 2^i, so 1101 means 8 + 4 + 0 + 1.

Bit index3210
Weight8421
Bits of 131101

Bit 0 is the least significant bit (LSB); the leftmost 1 is the most significant bit (MSB).

print(bin(13))             # 0b1101
print(format(13, "08b"))   # 00001101 (padded to 8 digits)
print(int("1101", 2))      # 13
print((13).bit_length())   # 4 bits needed

Two's complement

Almost every machine stores negative integers in two's complement: in n bits, -x is "flip every bit of x, then add 1", that is ~x + 1. With 8 bits, 5 is 00000101 and -5 is 11111011. One adder handles both signs and zero has a single encoding. An n-bit signed integer covers -2^(n-1) to 2^(n-1) - 1, so a 32-bit int runs from -2147483648 to 2147483647. A set top bit means the value is negative.

Core operators

OperationSymbolResult bit is 1 whenExample (12, 10)
AND&both bits are 11100 & 1010 = 1000 (8)
ORvertical barat least one bit is 11100, 1010 give 1110 (14)
XOR^the bits differ1100 ^ 1010 = 0110 (6)
NOT~flips every bit~12 = -13
Left shift<<bits move left, zeros enter
¿Tienes preguntas sobre este capítulo?
Capítulo siguienteHow It Works
3 << 2 = 12
Right shift>>bits move right12 >> 2 = 3

x << k equals x * 2^k, and for non-negative x, x >> k equals x // 2^k. Because of two's complement, ~x == -x - 1.

a, b = 12, 10
print(a & b, a | b, a ^ b)   # 8 14 6
print(~a)                    # -13
print(3 << 2, 12 >> 2)       # 12 3
print(-12 >> 1)              # -6: arithmetic shift keeps the sign

Working with a single bit

All four basic single-bit operations use the mask 1 << i:

  • set: x | (1 << i)
  • clear: x & ~(1 << i)
  • toggle: x ^ (1 << i)
  • test: (x >> i) & 1, or (x & (1 << i)) != 0
x = 0b1010
print(bin(x | (1 << 0)))    # 0b1011
print(bin(x & ~(1 << 1)))   # 0b1000
print(bin(x ^ (1 << 3)))    # 0b10
print((x >> 3) & 1)         # 1

When to reach for it

  • Representing a set of about 20 items as one integer and visiting every subset
  • Packing many on/off states (permissions, options, feature flags) into one value
  • Fast checks: power of two, odd or even, remainder modulo 2^k via x & (2^k - 1)
  • XOR puzzles where every value appears in pairs except one

Vocabulary

  • Mask: an integer with only the bits of interest set. A mask that encodes a set is a bitmask.
  • Popcount: the number of 1 bits, also called the Hamming weight.
  • Lowest set bit: the rightmost 1, obtained with x & -x.
  • Logical vs arithmetic shift: a right shift that fills with zeros is logical; one that copies the sign bit is arithmetic.

Differences between languages

The same expression can behave differently across languages. Python integers are unbounded, so 1 << 100 is exact, and negatives act as if they had infinitely many leading 1s. JavaScript converts operands to 32-bit signed integers first, so 1 << 31 is negative and >>> 0 reads a result as unsigned. Java's int is also 32 bits, with >>> as the zero-filling shift. In C++, unsigned types keep you clear of overflow and undefined behavior. The implementation and real-world chapters cover the details.

Summary

Bit manipulation views integers as bit arrays and works on them with AND, OR, XOR, NOT and shifts. Negative numbers use two's complement, so -x == ~x + 1. Once set, clear, toggle and test feel natural and you think in masks, subset enumeration and bitmask DP follow easily.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.