Skip to content

Bit operation module

Wang Renxin edited this page Mar 3, 2016 · 7 revisions

This is a demonstration about how to implement a bit operation module 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_reg_fun(bas, bit_and);
mb_reg_fun(bas, bit_or);
mb_reg_fun(bas, bit_not);
mb_reg_fun(bas, bit_xor);
mb_reg_fun(bas, bit_lshift);
mb_reg_fun(bas, bit_rshift);

Note:

Since MY-BASIC use signed int for int_t as default, you might need to redefine int_t to support precise unsigned bit operations and mb_strtol as well.

Clone this wiki locally