LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

bin string to hex string

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
}
}

0 Kudos
Message 1 of 2
(1,079 Views)

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) {
}

 

 

 

 



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 2
(1,030 Views)