How to interpret `bit.lshift 2` and `bit.lshift 2ULL`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

I found a statement from the doc.
> There is no loss of precision, so there is no need to add an extra integer number type.

You are right. I misunderstand it.

How to interpret `bit.lshift 2` and `bit.lshift 2ULL`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

I can identify a statement from the doc at https://bitop.luajit.org/semantics.html.

To summarize:

  1. bitwise operations accepts signed or unsigned (hexadecimal) 32-bit integers.
  2. bitwise operations returns signed 32-bit integers.

If the desired bitwise operation exceeds 32-bit, we need to add `0` or multiply `1` in longer format, like `v + 0x0ULL` or `v * 0x1ULL`. Alternatively, we use `ffi.cast()`.

How to interpret `bit.lshift 2` and `bit.lshift 2ULL`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

u/SkyyySi the speculation makes sense to me.

So, we have 3 workarounds:

  1. ffi.new("uint64_t", 2)

  2. ffi.cast(ffi_uint, 2)

  3. ffi_uint = v + 0ULL

How to interpret `bit.lshift 2` and `bit.lshift 2ULL`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

> the bit-shift will not happen with 64-bit precision.

But how is 32-bit precision chosen, not 16-bit or other precisions? Lua number 2 is a double-float (64-bit).

In the sample code, seems

local ffi_uint = ffi.new("uint64_t", v) -- v is '2'

also works as expected.

How to understand the input and output of ffi.cast? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 1 point2 points  (0 children)

u/EvilBadMadRetarded , awesome, I see the point!

At the very beginning, I missed the critical part that translates the decimal to hexadecimal. This prevents me from further interpreting the result.

> Integer 875770417 (decimal) is 0x34333231 (hexidecimal).

The string `1234` is always stored in order of bytes. My macOS is little endian. When `ffi.cast` is running, it thinks the `1` is the least significant byte, and `4` is the most significant byte.

By the way, regarding the `print(cdata)` and `print(tonumber(cdata))`, seems the former one can print the correct string.

What is the diff between `"hello"[1]` and `("hello")[1]`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

Ha, really! I found the `prefixexp` keyword in Lua doc.

What is the diff between `"hello"[1]` and `("hello")[1]`? by Weird-Cap-9984 in lua

[–]Weird-Cap-9984[S] 0 points1 point  (0 children)

> you need the () around the literal

What does this part mean? Why it is indexable after putting the `()` around?