Thomas Hur
Thomas Hur

Reputation: 11

Most efficient way to change endian-ness of a string?

I have a binary string of 64 characters (1000000011000100101000101110011010010001110101011011001111110111) and I would like to change the endian-ness of this binary string based on a variable called bits.

For example, if I have a string of 64 characters:

if bits = 8, each 8 bits are reversed and the program would print out

8-1, 16-9, 24-17, 32-25

if bits = 16, each 8 bits are reversed and the positions of the first byte and second byte are swapped

16-9, 8-1, 32-25, 24-17, 48-41, 40-33, 64-57, 56-49

if bits =32, each 8 bits are reversed and the fourth byte is outputted first, then the 3rd, 2nd, 1st, followed by the 8th, 7th, 6th, 5th

32-25, 24-17, 16-9, 8-1, 64-57, 56-49, 48-41, 40-33

and if bits = 64, the entire string is reversed

64-57, 49-56, etc

All I have is a string reverse function, and I'm not sure how I would go about from here. Any help would be appreciated!

char *strrev(char *str){
  if (!str || ! *str) return str;
  char ch;
  int i = strlen(str) - 1, j = 0;
  while (i > j){
    ch = str[i];
    str[i]=str[j];
    str[j]=ch;
    i--;
    j++;
  }
  return str;
}

Upvotes: 0

Views: 81

Answers (1)

Jeff
Jeff

Reputation: 1264

Based on your examples you want:

bits = 8:
    8-1, 16-9, 24-17, 32-25
bits = 16:
    16-1, 32-17
bits = 32:
    32-1, 64-33
bits = 64:
    64-1

This looks like you'll need two loops. The outer loop for each group of bits and the inner loop to reverse them:

void swap(char *str, int i, int j) {
    char tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
}

char *transform(char *str, int bits) {
    int n = strlen(str);
    for (int i = 0; i < n; i += bits) {
        for (int j = 0; j < bits / 2; j++) {
            swap(str, i + j, i + bits - 1 - j);
        }
    }
    return str;
}

Upvotes: 1

Related Questions