function to swap each 4 bytes of the ram

team, i have this function to swap each 4 bytes of the ram, void swapBytes(uint8_t *array, size_t length) { if (length % 4 != 0) { // Ensure the length is a multiple of 4 printf("Array length must be a multiple of 4.\n"); return; } for (size_t i = 0; i < length; i += 4) { uint8_t temp0 = array[i]; uint8_t temp1 = array[i + 1]; uint8_t temp2 = array[i + 2]; uint8_t temp3 = array[i + 3]; array[i] = temp3; array[i + 1] = temp2; array[i + 2] = temp1; array[i + 3] = temp0; } } what do you thin there is beeter way to do it or any enhancement
1 Reply
Enthernet Code
Enthernet Code6mo ago
Your code is accurate and should work as intended, but just in case, here's an improved version
#include <stdio.h>

void swapBytes(uint8_t *array, size_t length)
{
// Check if the array is NULL
if (array == NULL)
{
printf("Array pointer is NULL.\n");
return;
}

// Ensure the length is a multiple of 4
if (length % 4 != 0)
{
printf("Array length must be a multiple of 4.\n");
return;
}

for (size_t i = 0; i < length; i += 4)
{
// Swap the bytes within each group of 4
uint8_t temp0 = array[i];
uint8_t temp1 = array[i + 1];
uint8_t temp2 = array[i + 2];
uint8_t temp3 = array[i + 3];

array[i] = temp3;
array[i + 1] = temp2;
array[i + 2] = temp1;
array[i + 3] = temp0;
}
}
#include <stdio.h>

void swapBytes(uint8_t *array, size_t length)
{
// Check if the array is NULL
if (array == NULL)
{
printf("Array pointer is NULL.\n");
return;
}

// Ensure the length is a multiple of 4
if (length % 4 != 0)
{
printf("Array length must be a multiple of 4.\n");
return;
}

for (size_t i = 0; i < length; i += 4)
{
// Swap the bytes within each group of 4
uint8_t temp0 = array[i];
uint8_t temp1 = array[i + 1];
uint8_t temp2 = array[i + 2];
uint8_t temp3 = array[i + 3];

array[i] = temp3;
array[i + 1] = temp2;
array[i + 2] = temp1;
array[i + 3] = temp0;
}
}
Want results from more Discord servers?
Add your server