Extraer un nibble de 8 bits en C

Guía práctica para extraer un nibble de 4 bits en C: máscaras 0x0F, errores típicos (pos y desplazamientos) y ejemplos con 0xAB; versión con macros para firmware

17 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Al enfrentar el problema Extraer un nibble de 8 bits en C pensé que sería sencillo: un nibble son 4 bits. Sin embargo, al trabajar el ejercicio descubrí confusiones sobre representación numérica, máscaras y trampas sintácticas de C. Aquí explico el razonamiento, los errores comunes y la solución correcta, con ejemplos prácticos.

Descripción del problema: se recibe un registro de 8 bits con valores entre 0 y 255 y una posición pos donde pos = 0 indica extraer el nibble inferior bits 0-3 y pos = 1 indica extraer el nibble superior bits 4-7. La salida debe ser el valor del nibble en decimal entre 0 y 15. Ejemplo: reg = 0xAB pos = 0 devuelve 11; reg = 0xAB pos = 1 devuelve 10.

Hexadecimal frente a decimal y binario: 0xAB en binario es 1010 1011 y en decimal 171. Al separar nibbles: nibble superior 1010 es 0xA decimal 10; nibble inferior 1011 es 0xB decimal 11. Un error común es confundir la representación visual hex con la salida decimal esperada: el resultado 11 es decimal, no el binario 11 que sería decimal 3.

Máscaras y la regla general: para un campo de N bits la máscara se obtiene con la fórmula (1 << N) - 1. Ejemplos: 3 bits (1 << 3) - 1 = 7 = 0x07 binario 0000 0111; 4 bits (1 << 4) - 1 = 15 = 0x0F binario 0000 1111; 8 bits (1 << 8) - 1 = 255 = 0xFF. Para extraer un nibble la máscara correcta es 0x0F.

Errores típicos en C y ejemplo de código con fallos: // Código inicial con errores unsigned char extractNibble(unsigned char reg,int pos){ if(pos = 0){ unsigned char lower = (reg >> 0) & 0x07; return lower;} else{ unsigned char higher = (reg >> 6) & 0x07; return higher;}} En ese fragmento hay tres problemas frecuentes: se usa la asignación en la condición if pos = 0 en vez de la comparación pos == 0; la máscara 0x07 es de 3 bits cuando el nibble necesita 4 bits 0x0F; y el desplazamiento para el nibble superior debe ser 4 y no 6.

Código corregido (función): #include <stdio.h> unsigned char extractNibble(unsigned char reg,int pos){ if(pos == 0){ return reg & 0x0F;} else { return (reg >> 4) & 0x0F;} } Esta versión devuelve 11 para reg = 0xAB pos = 0, 10 para reg = 0xAB pos = 1 y 15 para reg = 0xFF pos = 0.

Estilo firmware con macros: #define NIBBLE_MASK 0x0F #define NIBBLE_BITS 4 #define EXTRACT_NIBBLE(reg,pos) (((reg) >> ((pos) * NIBBLE_BITS)) & NIBBLE_MASK) unsigned char extractNibble(unsigned char reg,int pos){ return EXTRACT_NIBBLE(reg,pos); } Esta aproximación elimina condicionales y deja explícita la relación entre posición, desplazamiento y máscara, práctica habitual en desarrollo embebido.

Aprendizajes clave: un nibble son 4 bits y siempre se enmascara con 0x0F tras desplazar; los valores de registro pueden mostrarse en hexadecimal pero la salida suele interpretarse en decimal; la fórmula (1 << N) - 1 genera máscaras N bits; cuidado con = frente a == en C; y en firmware las macros ayudan a mantener el código claro y consistente.

Sobre Q2BSTUDIO: en Q2BSTUDIO somos una empresa de desarrollo de software que ofrece aplicaciones a medida y software a medida para proyectos embebidos y de empresa. Además trabajamos soluciones de inteligencia artificial y ofrecemos servicios de ia para empresas y agentes IA diseñados para automatizar tareas y mejorar procesos. Si buscas desarrollar una solución a medida conoce nuestras capacidades en desarrollo de aplicaciones y software multiplataforma y para proyectos de inteligencia artificial visita Inteligencia artificial. Complementamos estos servicios con experiencia en ciberseguridad, pentesting, servicios cloud aws y azure, servicios inteligencia de negocio y power bi para crear soluciones seguras, escalables y orientadas a datos.

Si trabajas con firmware o sistemas embebidos y necesitas apoyo para crear software fiable, integrar modelos de IA, asegurar la plataforma con ciberseguridad o desplegar en la nube con servicios cloud aws y azure, en Q2BSTUDIO podemos ayudarte desde el diseño hasta la puesta en producción. Palabras clave que nos definen: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

Conclusión: un ejercicio aparentemente simple como extraer un nibble enseña mucho sobre manipulación de bits, sistemas numéricos y peligros sintácticos en C. Practicar estos casos mejora la calidad del firmware y evita errores que en el mundo real pueden afectar periféricos como UART o ADC. Si necesitas ayuda profesional para desarrollar firmware, soluciones IA o asegurar tu infraestructura, contacta con Q2BSTUDIO y convertimos tu reto en un proyecto exitoso.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat