typescriptrustbit-manipulationbitwise-or

TypeScript equivalent of `u32` numerical suffix


I'm in the process of converting parts of an old Rust application to TypeScript and in the process I found this in the Rust program:

seed | 0x80000000u32

Although, this doesn't work in TypeScript (I assume due to how TS has the Number object instead of u8,u32,u64...) and yields these unfruitful results:

Cannot find name 'u32'

I've tried things such as conversions, like >>> 0 on the number and then using the Bitwise OR operator, although nothing has come out of it. Can I preform this operation in TypeScript? If not is there some other work around for it?


TypeScript code

// fog.ts ~ checkWaterFog()
import seedrandom from "seedrandom";
import { Month, Island, monthToNumber } from "./types.ts";

export function checkWaterFog(
  island: Island,
  day: number,
  month: Month,
  year: number
) {
  var rng = seedrandom(
    `${year << 8}${monthToNumber(month) << 8}${day << 8}${island.seed | 0x80000000u32}`
  );
  
  // First two results are unused
  rng();
  rng();
  return (rng() & 1) == 1;
}

Month is just January - December and monthToNumber() converts Month to a Number 1-12.


Rust code

// fog.rs ~ check_water_fog()
pub fn check_water_fog(seed: u32, year: u16, month: u8, day: u8) -> bool {
    let mut rng = Random::with_state(
        (year as u32) << 8,
        (month as u32) << 8,
        (day as u32) << 8,
        seed | 0x80000000u32
    );

    // First two results are unused
    rng.roll();
    rng.roll();
    (rng.roll() & 1) == 1
}

Solution

  • Can I preform this operation in TypeScript? If not is there some other work around for it?

    You can just remove the suffix.

    1. the suffix is not actually necessary in Rust, I'm not sure why the original author put it: seed is a u32, the expected result is a u32, the playground infers that the literal should be a u32 as well

    2. typescript does not have the zoo of fixed-size integers Rust has, from Javascript it inherits that all numbers are doubles (64-bit floats), so it does not have the suffixes either, or the need for conversions

    3. although as prog-fh comments javascript runtimes and JITs will use bitwise expressions to internally type the results as 32-bit integers (because javascript only defines bitwise expressions on 32-bit integers)

    4. one thing to be aware and wary of, is that this internal operation works on signed integers only, and uses two's complement representation, this also influences the conversion from external Number to internal int32 (you can get the details from the spec, specifically the NumberBitwiseOp abstract operation and its sub-operations)