add int2float and float2int conversion ops

This commit is contained in:
zongor 2025-06-08 23:26:42 -04:00
parent af01b5afae
commit 39b6a1f15f
1 changed files with 21 additions and 7 deletions

View File

@ -1,4 +1,3 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
@ -24,7 +23,9 @@ typedef enum {
OP_SUB_F32, /* dest = src1 - src2 */
OP_MUL_F32, /* dest = src1 * src2 */
OP_DIV_F32, /* dest = src1 / src2 */
OP_MOV, /* dest = src1 */
OP_F32_TO_INT, /* dest = src1 as int */
OP_INT_TO_F32, /* dest = src1 as f32 */
OP_MOV, /* dest = src1 */
OP_JMP, /* jump to address src1 unconditionally */
OP_JGZ, /* jump to address dest if src1 > 0 */
OP_INT_TO_STRING, /* dest = src1 as str */
@ -69,7 +70,7 @@ void pack_string(const char *str, uint32_t length, uint32_t dest_addr) {
uint32_t i = 0;
while (i < length) {
char ch = str[i++];
if (ch == '\0' || ch == EOF) {
if (ch == '\0') {
uint32_t word = memory[buffer_addr + word_index].u;
word = set_char(word, char_index, '\0');
memory[buffer_addr + word_index].u = word;
@ -85,7 +86,6 @@ void pack_string(const char *str, uint32_t length, uint32_t dest_addr) {
char_index = 0;
word_index++;
}
length++;
}
}
@ -142,6 +142,16 @@ void run_vm() {
}
memory[dest_addr].f = memory[src1_addr].f / memory[src2_addr].f;
break;
case OP_F32_TO_INT: {
float tmp = memory[src1_addr].f;
memory[dest_addr].u = (uint32_t)tmp;
break;
}
case OP_INT_TO_F32: {
int tmp = memory[src1_addr].u;
memory[dest_addr].f = (float)tmp;
break;
}
case OP_HALT:
return;
case OP_MOV:
@ -238,9 +248,13 @@ int main() {
memory[i++].u = 100;
memory[i++].u = OP_JGZ;
memory[i++].u = 100;
memory[i++].u = 4;
memory[i++].u = 4;
memory[i++].u = OP_F32_TO_STRING;
memory[i++].u = 0;
memory[i++].u = 0;
memory[i++].u = OP_F32_TO_INT;
memory[i++].u = 103;
memory[i++].u = 0;
memory[i++].u = 103;
memory[i++].u = OP_INT_TO_STRING;
memory[i++].u = 103;
memory[i++].u = 0;
memory[i++].u = 104;