Not disclosed Interview Question
Tech LeadsCountry: India
Should be straight forward. One character takes 8 bytes. An integer is 4 bytes so it can hold maximum of 4 characters. That means first 8 bytes of the integer will store first char, the next bytes of the integer will store the next char and so on. So you after storing every char you will have right shift the integer with 8 bytes and perform an OR operation to store the next character so you do not corrupt the previously stored character. Something like following
int num = 0;
if ( str.length() <= 4 ) {
for ( int i = 0; i < str.size(); i++ ) {
int char_i = (int)str[i];
char_i = char_i << (i*8);
num = num | char_i;
}
}
Now figure out how you can read characters from this integer.
Should be straight forward. One character takes 8 bytes. An integer is 4 bytes so it can hold maximum of 4 characters. That means first 8 bytes of the integer will store first char, the next bytes of the integer will store the next char and so on. So you after storing every char you will have right shift the integer with 8 bytes and perform an OR operation to store the next character so you do not corrupt the previously stored character. Something like following
int num = 0;
if ( str.length() <= 4 ) {
for ( int i = 0; i < str.size(); i++ ) {
int char_i = (int)str[i];
char_i = char_i << (i*8);
num = num | char_i;
}
}
Now figure out how you can read characters from this integer.
Actually an int is not guaranteed to be 4 bytes on all platforms, so we can ise stdint.h's uint32_t to get sure 4bytes width
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
uint32_t str_to_int(char *in) {
if (!in)
return 0;
uint32_t ret = 0;
int i = 0;
while (i < 4) {
ret |= (in[i] << 8 * i++);
}
return ret;
}
void int_to_str(uint32_t in, char *out) {
if (!out)
return;
int i = 0;
while (i < 4) {
out[i++] = in >> 8 * i;
}
}
int main(int argc, char **argv) {
char *in = "ABxy";
uint32_t int_out = str_to_int(in);
printf("%x\n", int_out);
char *out = malloc(4);
int_to_str(int_out, out);
printf("%s\n", out);
free(out);
return 0;
}
In C, integers are 2 to 4 bytes long. ASCII characters are 1 byte long. We can pack 4 bytes into one 4bytes integer.
- NoOne December 26, 2018