Use byteswap to implement conversion to and from bytes
Cleaner looking implementations
This commit is contained in:
26
lib/base.c
26
lib/base.c
@@ -29,39 +29,29 @@ word_t word_byteswap(const word_t w)
|
|||||||
hword_t convert_bytes_to_hword(const byte_t *bytes)
|
hword_t convert_bytes_to_hword(const byte_t *bytes)
|
||||||
{
|
{
|
||||||
hword_t h = 0;
|
hword_t h = 0;
|
||||||
if (LITTLE_ENDIAN)
|
|
||||||
memcpy(&h, bytes, HWORD_SIZE);
|
memcpy(&h, bytes, HWORD_SIZE);
|
||||||
else
|
if (!LITTLE_ENDIAN)
|
||||||
for (size_t i = 0; i < HWORD_SIZE; ++i)
|
h = hword_byteswap(h);
|
||||||
h |= ((hword_t)(bytes[i]) << (8 * i));
|
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
word_t convert_bytes_to_word(const byte_t *bytes)
|
word_t convert_bytes_to_word(const byte_t *bytes)
|
||||||
{
|
{
|
||||||
word_t h = 0;
|
word_t h = 0;
|
||||||
if (LITTLE_ENDIAN)
|
|
||||||
memcpy(&h, bytes, WORD_SIZE);
|
memcpy(&h, bytes, WORD_SIZE);
|
||||||
else
|
if (!LITTLE_ENDIAN)
|
||||||
for (size_t i = 0; i < WORD_SIZE; ++i)
|
h = word_byteswap(h);
|
||||||
h |= ((word_t)(bytes[i]) << (8 * i));
|
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
void convert_hword_to_bytes(hword_t w, byte_t *bytes)
|
void convert_hword_to_bytes(hword_t w, byte_t *bytes)
|
||||||
{
|
{
|
||||||
if (LITTLE_ENDIAN)
|
hword_t h = LITTLE_ENDIAN ? w : hword_byteswap(w);
|
||||||
memcpy(bytes, &w, HWORD_SIZE);
|
memcpy(bytes, &h, HWORD_SIZE);
|
||||||
else
|
|
||||||
for (size_t i = 0; i < HWORD_SIZE; ++i)
|
|
||||||
bytes[i] = WORD_NTH_BYTE(w, i);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void convert_word_to_bytes(word_t w, byte_t *bytes)
|
void convert_word_to_bytes(word_t w, byte_t *bytes)
|
||||||
{
|
{
|
||||||
if (LITTLE_ENDIAN)
|
word_t h = LITTLE_ENDIAN ? w : word_byteswap(w);
|
||||||
memcpy(bytes, &w, WORD_SIZE);
|
memcpy(bytes, &h, WORD_SIZE);
|
||||||
else
|
|
||||||
for (size_t i = 0; i < WORD_SIZE; ++i)
|
|
||||||
bytes[i] = WORD_NTH_BYTE(w, i);
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user