Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I am trying to make a simple stack-based virtual machine, and i want the stack to be an array of type int8_t, so that every element is 1 byte. But I don't want to exclusively work with bytes, i want 16-, 32-, and 64-bit numbers to work too, therefore i need bitmasks.

This is currently the code:
C++
#include <stdint.h>
#include <stdio.h>
#define STACKSIZE 65536

int8_t stack[STACKSIZE];
void push(int8_t);
int8_t pop();
void pushw(int16_t);
int16_t popw();
int64_t top = -1;

int main() {
	pushw(938);
	for (int i = 0; i < 10; i++)
	{
		printf("%d\n", stack[i]);
	}
	printf("\n\n%d", popw());
	return 0;
}

void push(int8_t x) {
	if (rsp == STACKSIZE - 1)
	{
		printf("Overflow!");
	}
	else
	{
		rsp++;
		stack[rsp] = x;
	}
}

int8_t pop() {
	if (rsp == -1) {
		printf("Underflow");
		return -1;
	}
	else {
		rsp--;
		return stack[rsp + 1];
	}
}

//LSB-MSB at push
//MSH-LSB at pop
void pushw(int16_t x) {
	push(x & 0x00FF);
	push(x & 0xFF00);
}

int16_t popw() {
	int16_t r = pop();
	r |= (pop() << 8);
	return r;
}


Expected output:
234 //I am not too good at decimal-binary conversion, but i think these are right
2
0
0
0
0
0
0
0
0


938


What i get instead:
-86
0
0
0
0
0
0
0
0
0

-22016


Please help.

What I have tried:

I have tried changing the order but then it gave me 0, -86 as the first two numbers and just returned -86 at the end with the popw();
Posted
Updated 26-Feb-23 9:21am

You need to shift the high order byte before pushing;

void pushw(int16_t x) {
push(x & 0x00FF);
push((x & 0xFF00) >> 8);
}
 
Share this answer
 
v2
Comments
Jamie Engel 25-Feb-23 13:12pm    
Now it actually pushes 2 values, but it's -86 and 3, and the popw is now -22013. Something must be wrong with either my popw function, or the first part of the pushw.
Mike Hankey 25-Feb-23 13:23pm    
You're pushing the LSB then the MSB and popping the LSB then the MSB. Should pop the other way around.

Reverse the pops and it should work the way you want.
Jamie Engel 25-Feb-23 13:39pm    
I did "r = (pop() << 8)" first, and then "r |= pop()" but now it just gives me -86.
CPallini 25-Feb-23 13:43pm    
5.
Another option is to use a union which is described here.[^]

This is an example :
C
typedef union uShortBytes
{
    UCHAR       Bytes[2];
    WCHAR       Wchar;
    UINT16      Ushort;
    struct
    {
        UCHAR   Low;
        UCHAR   High;
    } HiLo;
} ShortBytes;


    ShortBytes sb;
    sb.Ushort = 938;
    printf( " low order byte is %3u\n", sb.HiLo.Low );
    printf( "high order byte is %3u\n", sb.HiLo.High );
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900