Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Last active May 28, 2022 01:35
Show Gist options
  • Save Per48edjes/0f941dddc308ed7e98eb8b57b9f31a8e to your computer and use it in GitHub Desktop.
Save Per48edjes/0f941dddc308ed7e98eb8b57b9f31a8e to your computer and use it in GitHub Desktop.
Encoding strings as integers, vice versa in C
#include <stdio.h>
#include <string.h>
/*
* Extra credit: If an array of characters is 4 bytes long, and an integer is 4
* bytes long, then can you treat the whole in_name array like it’s just an
* integer?
*/
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Incorrect or missing arguments!\n");
return 1;
}
else
{
char *in_name = argv[1];
unsigned long bits[strlen(in_name)];
unsigned char out_name[strlen(in_name)];
// Convert from string to integer representation
unsigned long int_repr = 0;
for (int i = 0, count = strlen(in_name); i < count; ++i)
{
bits[i] = (unsigned long)in_name[i] << (count - i - 1) * 8;
int_repr += bits[i];
}
printf("The integer representation of '%s' is %lu.\n", in_name, int_repr);
// Convert from integer to string representation
for (int i = 0, count = strlen(in_name); i < count; ++i)
{
out_name[i] = (int_repr >> ((count - i - 1) * 8)) & 0xFF;
}
printf("Converting %lu into array of `char`s yields '%s'! \n", int_repr, out_name);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment