I would like to convert signed int to signed char efficiently in javascript. I've tried:
function convertByModular(n) {
return ((((n + 128) % 256) + 256) % 256) - 128;
}
function convertByTypedArray(n) {
return new Int8Array([n])[0];
}
console.log(convertByModular(-129));
console.log(convertByTypedArray(-129));
Is there other efficient ways to convert signed int to signed char? (especially using bit operators)
You can convert a signed integer to a signed char in JavaScript by using the <<
(left shift) and >>
(right shift) operators to limit the value of integers. For example, to convert a signed integer x
to a signed char, you can do the following:
function toSignedChar(x) {
return (x << 24 >> 24); // 24 bits left shift and then 24 bits right shift
}
// For example
console.log(toSignedChar(300)); // -28
console.log(toSignedChar(-300)); // 28
In the above example, x
is converted to an 8-bit signed integer (signed char) using 24 bits left shift and then 24 bits right shift. This will retain the last 8 bits of x
and discard the remaining bits, producing a signed integer of equivalent value.