community, I have little experience with C and I am on the learning curve right now.
I am working on a little project that involves dividing a 32-char string into 4 strings of 8 chars each in C.
The 32-char string should resemble a 32-bit instruction. Those "32 bits" are divided into 4 "8-bit" strings that I want to print out as Hex. The code below is what I got so far. The data types I am using are the ones I am using in the rest of my code. I intend to feed the unsigned char t
variable into an Substitution Box program that will give me equivalent of that t
char from the S-Box lookup table.
The code below seems to me like it should work
unsigned char inst[] = "10101010101010101111111100111101";
unsigned char in[8];
for (int i = 0; i < 33; i++){
if (i%8 == 0 && i != 0) {
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("%x \n", t);
}
in[i%8] = inst[i];
printf("%c ", in[i%8]);
}
but the output looks like this:
1 0 1 0 1 0 1 0 3d
1 0 1 0 1 0 1 0 3d
1 1 1 1 1 1 1 1 3d
0 0 1 1 1 1 0 1 3d
I can see that in[i%8] = inst[i];
line is reading the chars
from inst[]
correctly, but the
if (i%8 == 0 && i != 0) {
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("%x \n", t);
}
conditional statement prints the wrong hex. The output should look like something like this
1 0 1 0 1 0 1 0 aa
1 0 1 0 1 0 1 0 aa
1 1 1 1 1 1 1 1 ff
0 0 1 1 1 1 0 1 3d
Any help would be appreciated.
The problem is your in
is not NUL
terminated.
Thus passing in
to strol
invokes the undefined behavior.
Do as below.
unsigned char in[9]; //+1 to hold the NUL char.
....
if (i%8 == 0 && i != 0) {
in[8] = '\0'; //NUL terminate the string.
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("%x \n", t);
}
Problems with the current code:
char in[4][8+1];
and not char in[8]
. You need room for null termination.This seems to be the requirements:
In which case you can simply iterate 4 times over the input string:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
const char* inst = "10101010101010101111111100111101";
char in [4][8+1];
puts("Bin Hex");
for(size_t i=0; i<4; i++)
{
memcpy(in[i], &inst[i*8], 8);
in[i][8] = '\0';
unsigned long val = strtoul(in[i], NULL, 2);
printf("%.8s %.2lX\n", in[i], val);
}
}
Output:
Bin Hex
10101010 AA
10101010 AA
11111111 FF
00111101 3D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With