Skip to content

Bit operation module

Wang Renxin edited this page May 31, 2022 · 7 revisions

This page shows how to implement bit operations with MY-BASIC.

Add implementation functions:

static int _bit_and(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;
	int_t n = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));
	mb_check(mb_pop_int(s, l, &n));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, m & n));

	return result;
}

static int _bit_or(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;
	int_t n = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));
	mb_check(mb_pop_int(s, l, &n));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, m | n));

	return result;
}

static int _bit_not(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, ~m));

	return result;
}

static int _bit_xor(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;
	int_t n = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));
	mb_check(mb_pop_int(s, l, &n));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, m ^ n));

	return result;
}

static int _bit_lshift(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;
	int_t n = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));
	mb_check(mb_pop_int(s, l, &n));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, m << n));

	return result;
}

static int _bit_rshift(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	int_t m = 0;
	int_t n = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_int(s, l, &m));
	mb_check(mb_pop_int(s, l, &n));

	mb_check(mb_attempt_close_bracket(s, l));

	mb_check(mb_push_int(s, l, m >> n));

	return result;
}

Register them:

mb_register_func(bas, "BIT_AND", _bit_and);
mb_register_func(bas, "BIT_OR", _bit_or);
mb_register_func(bas, "BIT_NOT", _bit_not);
mb_register_func(bas, "BIT_XOR", _bit_xor);
mb_register_func(bas, "BIT_LSHIFT", _bit_lshift);
mb_register_func(bas, "BIT_RSHIFT", _bit_rshift);

Note:

Since MY-BASIC uses signed int for int_t as default, you might need to redefine int_t to support bit operations of unsigned integer, and don't forget to redefine mb_strtol as well.

Clone this wiki locally