I am working on a byte editor like DataView but with more features and I was wondering how to detect if a TypedArray was signed or not.

I already have this,

const signedTypes = new Set([
    Int8Array,
    Int16Array,
    Int32Array,
    BigInt64Array
]);

function isSigned(TypedArray) {
    return signedTypes.has(TypedArray.constructor);
}

But this seems too manual - for example, if there was a new signed TypedArray like 20 years into the future I'm going to have to go back to my source code and add it into the list.

I could also check if the name matches Int or BigInt but that feels too hacky.

Feedback is appreciated, Thanks 🙏

2 Replies 2

Clearly if the array is of length 0 it doesn't matter. So if the length is at least 1, you can save the value at position 0, put -1 in it, then get the value back out. If the value you get is negative, it's a signed array; otherwise not.

function isSigned(typed) {
   if (!typed?.length) return false;
   const save = typed[0];
   typed[0] = -1;
   const rv = typed[0] < 0; // it's signed if this is true
   typed[0] = save;
   return rv;
}

Thanks to Pointy I have found a good solution.

function isSigned(TypedArray) {
    const sample = TypedArray.BYTES_PER_ELEMENT === 8 ? [-1n] : [-1];
    const array = new TypedArray(sample);
    return ArrayBuffer.isView(array) && array[0] < 0;
}

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.