typescriptnumbersbitoperation

typescript number type with bit operations


in typescript, as the number type can be int or float, so what if I use number type with bit operations

I have see some library use this

const a = 1.23
const b = a | 0

Sorry for the inaccurate expression, I'm just curious about this feature and not actually applying it. If I think about it from a memory perspective, like in C++, If I use

a |= 0

I can convert a into its binary form, Each bit is ORed with 0 and get the result. But what's the memory struct in Js, If a = 1.23, what's the binary form, and why the ORed will like a trunc operation?

and the result of b is 1, so can I use this method as a method of taking integers

I think I found the answer here: https://stackoverflow.com/a/52650645/28235582


Solution

  • Yes, you can use bitwise operations in TypeScript as a method of converting floating-point numbers to integers! The bitwise OR operation (| 0) is commonly used to truncate a floating-point number to an integer.