Similar Posts

Subscribe
Notify of
4 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
JanaL161
10 months ago

CVTTS2SIConvhet with trun Scalar Single precision floating-point value to integer) is an x86 processor instruction, which is a Number of floating points (IEEE 754 binary32) is converted into an integer (with sign, 32 or 64bit depending on the target register width) and thereby rounds to zero:

https://www.felixcloutier.com/x86/cvttss2si

This has the background that such numbers are processed completely differently in a modern CPU: https://de.wikipedia.org/wiki/X87. And therefore occasionally need to be converted back and forth.

JanaL161
10 months ago
Reply to  MissyCooper

Yes, it is specified “truncation”, so the end is “hacked”: https://de.wikipedia.org/wiki/Trunkierung_(Mathematics). This has the effect of rounding against zero (even if “normal” rounding would give a different result):

8.92 -> 8
-2.57 -> -2

A practical example:

; cvttss2si demo
; ------------------------------------------------------
; Author: JanaL161
; Date: 2024-05-30
; ------------------------------------------------------
; compilation instructions (x86_64-pc-linux-gnu)
;
; nasm -f elf64 -g -F dwarf -o cvttss2si.o cvttss2si.asm
; gcc -nostartfiles -no-pie -o cvttss2si cvttss2si.o -lc
; ------------------------------------------------------

section .data
  float_a dd 8.92
  float_b dd -2.57
  int_a   dd 0
  int_b   dd 0

  format_str db "val: %d", 10, 0

section .text
  extern printf
  global _start

_start:
  ; load float_a into xmm0 and float_b into xmm1
  mov eax, [float_a]
  movd xmm0, eax

  mov eax, [float_b]
  movd xmm1, eax

  ; run cvttss2si and store the result into int_a and int_b respectively
  cvttss2si eax, xmm0
  mov [int_a], eax

  cvttss2si eax, xmm1
  mov [int_b], eax

  ; print int_a and int_b
  mov rdi, format_str
  mov rsi, [int_a]
  call printf

  mov rdi, format_str
  mov rsi, [int_b]
  call printf

  ; exit with 0
  mov rax, 60
  xor rdi,rdi
  syscall

Issue:

val: 8
val: -2
JanaL161
10 months ago

There is also the instruction CVTSS2SI (only a T) that can work with different round modes:

https://imgur.com/a/WhA8isv