Last active
December 18, 2015 05:18
-
-
Save simonwhitaker/5731617 to your computer and use it in GitHub Desktop.
A sample command-line OSX app for switching the endianness of an input file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
int main(int argc, const char * argv[]) { | |
@autoreleasepool { | |
// Declare some config values; the input and output file paths and the | |
// number of bytes per word | |
NSString *inputFile = @"/Users/simon/Desktop/input.dat"; | |
NSString *outputFile = @"/Users/simon/Desktop/output.dat"; | |
NSUInteger bytesPerWord = 2; | |
// First, read in the data. I'm using NSMutableData so that I can write | |
// back to the same object later | |
NSMutableData *data = [NSMutableData dataWithContentsOfFile:inputFile]; | |
// Next, work out how many words are in the file. That'll be the length | |
// (in bytes) divided by the number of bytes per word. | |
NSUInteger numberOfWords = [data length] / bytesPerWord; | |
// Create a temporary array to store the bytes from each word while we | |
// reverse them | |
char *tempByteArray = calloc(bytesPerWord, 1); | |
// Now step through the data a word at a time | |
for (NSUInteger wordIndex = 0; wordIndex < numberOfWords; wordIndex++) { | |
// NSData lets you deal with ranges of bytes, so start by creating | |
// an NSRange that describes the range of bytes for the current word | |
NSRange wordRange = NSMakeRange(wordIndex * bytesPerWord, bytesPerWord); | |
// Load the bytes from that range into our buffer | |
[data getBytes:tempByteArray range:wordRange]; | |
// Now reverse the bytes in this word. Work through the first half of | |
// the byte array, swapping each byte with the corresponding byte from | |
// the far end of the array. So for example, with 64-bit words we'd | |
// swap indices 0 and 7, then 1 and 6, then 2 and 5, then 3 and 4. | |
for (NSUInteger byteIndex = 0; byteIndex < bytesPerWord / 2; byteIndex++) { | |
NSUInteger byteToSwapIndex = bytesPerWord - 1 - byteIndex; | |
// Swap the values at indices byteIndex and byteToSwapIndex | |
char temp = tempByteArray[byteIndex]; | |
tempByteArray[byteIndex] = tempByteArray[byteToSwapIndex]; | |
tempByteArray[byteToSwapIndex] = temp; | |
} | |
// Finally, write the newly-reversed word back to the original | |
// data object | |
[data replaceBytesInRange:wordRange withBytes:tempByteArray]; | |
} | |
// Release the memory allocated with calloc earlier. | |
free(tempByteArray); | |
// We've reversed endianness, Captain! Write to our output file. | |
[data writeToFile:outputFile atomically:NO]; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment