Fixed bug with converting (h)word to (h)word in terms of endian

While it helped with understanding to use unions as a safe way to
access the underlying bits, this shift based mechanism actually makes
more sense at a glance, particularly by utilising WORD_NTH_BYTE
This commit is contained in:
2024-04-28 20:57:41 +05:30
parent 7ca9f1b98b
commit 08c9726333
3 changed files with 10 additions and 71 deletions

View File

@@ -14,60 +14,16 @@
#include <string.h>
union hword_pun
hword_t hword_byteswap(const hword_t w)
{
hword_t h;
byte_t bytes[HWORD_SIZE];
};
union word_pun
{
word_t h;
byte_t bytes[WORD_SIZE];
};
hword_t hword_htobc(hword_t w)
{
if (LITTLE_ENDIAN)
return w;
union hword_pun x = {w};
union hword_pun y = {0};
for (size_t i = 0, j = HWORD_SIZE; i < HWORD_SIZE; ++i, --j)
y.bytes[j - 1] = x.bytes[i];
return y.h;
return WORD_NTH_BYTE(w, 3) | (WORD_NTH_BYTE(w, 2) << 8) |
(WORD_NTH_BYTE(w, 1) << 16) | (WORD_NTH_BYTE(w, 0) << 24);
}
hword_t hword_bctoh(hword_t w)
word_t word_byteswap(const word_t w)
{
if (LITTLE_ENDIAN)
return w;
union hword_pun x = {w};
union hword_pun y = {0};
for (size_t i = 0, j = HWORD_SIZE; i < HWORD_SIZE; ++i, --j)
y.bytes[j - 1] = x.bytes[i];
return y.h;
}
word_t word_htobc(word_t w)
{
if (LITTLE_ENDIAN)
return w;
union word_pun x = {w};
union word_pun y = {0};
for (size_t i = 0, j = WORD_SIZE; i < WORD_SIZE; ++i, --j)
y.bytes[j - 1] = x.bytes[i];
return y.h;
}
word_t word_bctoh(word_t w)
{
if (LITTLE_ENDIAN)
return w;
union word_pun x = {w};
union word_pun y = {0};
for (size_t i = 0, j = WORD_SIZE; i < WORD_SIZE; ++i, --j)
y.bytes[j - 1] = x.bytes[i];
return y.h;
return ((word_t)(hword_byteswap(WORD_NTH_HWORD(w, 0))) << 32) |
hword_byteswap(WORD_NTH_HWORD(w, 1));
}
hword_t convert_bytes_to_hword(const byte_t *bytes)

View File

@@ -166,25 +166,8 @@ word_t convert_bytes_to_word(const byte_t *);
*/
void convert_word_to_bytes(const word_t w, byte_t *buffer);
/**
@brief Convert a half word into bytecode format (little endian)
*/
hword_t hword_htobc(const hword_t);
hword_t hword_byteswap(const hword_t h);
/**
@brief Convert a half word in bytecode format (little endian) to
host format
*/
hword_t hword_bctoh(const hword_t);
/**
@brief Convert a word into bytecode format (little endian)
*/
word_t word_htobc(const word_t);
/**
@brief Convert a word in bytecode format (little endian) to host format
*/
word_t word_bctoh(const word_t);
word_t word_byteswap(const word_t w);
#endif

View File

@@ -431,9 +431,9 @@ size_t prog_write_bytecode(prog_t program, byte_t *bytes, size_t size_bytes)
if (size_bytes < PROG_HEADER_SIZE || prog_bytecode_size(program) < size_bytes)
return 0;
// Write program header i.e. the start and count
word_t start = word_htobc(program.start_address);
word_t start = word_byteswap(program.start_address);
*(bytes++) = start;
word_t count = word_htobc(program.count);
word_t count = word_byteswap(program.count);
*(bytes++) = count;
// Write instructions