11-03-2020 12:25 PM
Im trying to convert a bin string to a hex string. On the 7th iteration of the for loop the program it converts 0100 to fffffd30
im guessing it is a memory issue ?
#include <formatio.h>
#include <ansi_c.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
int hexnum;
char bstring[40]="0110000000000101100100010000";
int i = 0;
int j = 0;
unsigned char hexstr[40]="";
unsigned char four[10]="";
for(i = 0;i < 9;++i)
{
hexnum = 0;
strncpy(four, bstring + (i * 4),4);
for(j = 0;j < 4;++j)
{
hexnum += (four[j] - '0') << (3 - j);
}
Fmt(hexstr + i, "%x", hexnum); //hexstr = 60059104
}
}
11-04-2020 03:41 AM - edited 11-04-2020 03:45 AM
You are iterating on 9 items (for i = 0 to 8 ) but you don't have 9 tetrads in your string. You don't even have 8, which is what you should have to derive your 0x60059104 output string. So you are reading a part of bstring you haven't initialized with unpredictable results.
To solve the actual code you need to add "0100" at the end of bstring and to correct 'for' definition (i = 0 to 7 )
To have a more robust code I strongly suggest you use something like this in 'for' definition:
for (i = 0; i < strlen (bstring) / 4; ++i) {
}