Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
Optimize conversion from/to object<->number with bit twiddling

I'm looking to optimize my code that converts an object to a numerical represenation and vice versa. Currently I'm using the functions parseInt and toString but I would like to make this using bit twiddling. Do you have any idea how I can do this?

interface Item {
    flexType: number; // 1 bit
    flexNum: number; // 7 bits
    clearType: number; // 1 bit
    clearNum: number; // 7 bits
    weight: number; // 16 bits
}

const itemToNumber = (item: Item) => {
    const bitsFlexType = item.flexType.toString(2);
    const bitsFlexNum = item.flexNum.toString(2);
    const bitsClearType = item.clearType.toString(2);
    const bitsClearNum = item.clearNum.toString(2);
    const bitsWeight = item.weight.toString(2);
    return parseInt(
        [bitsFlexType, bitsFlexNum, bitsClearType, bitsClearNum, bitsWeight].join(
            ""
        ),
        2
    );
};

const numberToItem = (number: number) => {
    const bits = number.toString(2);
    const item: Item = {
        flexType: parseInt(bits[0], 2),
        flexNum: parseInt(bits.slice(1, 7), 2),
        clearType: parseInt(bits[7], 2),
        clearNum: parseInt(bits.slice(8, 15), 2),
        weight: parseInt(bits.slice(15), 2)
    };
    return item;
};

const numericItem = itemToNumber({
    flexType: 1,
    flexNum: 42,
    clearType: 0,
    clearNum: 100,
    weight: 1002
});
const item = numberToItem(numericItem);
console.log(item);

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda