Code Infinity

SAVE THE EARTH.............

Sunday, September 14, 2008

How to write a file in hexadecimal format?

I have written this post because i personally feet that this particular topic is left is most of the books while studying data file handling. When I was making my assembler "ASM Weaver" I had to work on writing hex files in C++.

So, here we gooooo...

Suppose you want to want a file "hex_file.com" in hex format & are aware of the content before run-time. Then, you can use the following procedure,
If you want to write 1C BA 25 (this is in hexadecimal format) then , 
 
write char(0xc1) to file and similliary the others.

    
Notice that to hexadecimal a number we add prefix 0x before that number. Notice,instead of directly writting the hex-number we have written char(0x1c) because c++ writes a file in decimal format so, by doing this we are actully writing the character equivalent of that hexadecimal number . The numbers are written in a pair because the represent the character.

But what if we don't know what to write in file before compile-time.In this case, you have to convert that number into a hexdecimal number store it in a variable and print the character equivalent as shown above.

Now problem arises how to convert the decimal into hexadecimal number. The solution of this problem can be found in the following code,


 
int len=0;
long a=0;

len = strlen(ch);
// if the number is 8bits then , this code will
//  store that data into a variable 'a'.

if(len<=3)
{
for(i=len;i>=0;--i)
{
if(isdigit(ch[i])) // ch has been defined, so don't confuse.
a += (ch[i]-'0')   *pow(power,j++);
else if(ch[i]>='a'&&ch[i]<='f')
a += (ch[i]-'a'+10)*pow(power,j++);
else if(ch[i]>='A'&&ch[i]<='F')
a += (ch[i]-'A'+10)*pow(power,j++);
}
fout<
}
else     // if the number is more than 8bits then it will do conversion.
{
j=len/2;
if(len==3)
j++;
char *sub;
while(j>=0)
{
int k=0,l=0;
//k=j*2;
long b=0;
sub=&ch[j];
for(i=1;i>=0;--i)
{
if(isdigit(sub[i]))
b += (sub[i]-'0')   *pow(power,l++);
else if(sub[i]>='a'&&sub[i]<='f')
b += (sub[i]-'a'+10)*pow(power,l++);
else if(sub[i]>='A'&&sub[i]<='F')
b += (sub[i]-'A'+10)*pow(power,l++);
}
fout<
j=j-2;
}

}

I have used this code, but if problem persists in its implementation then, you can mail. I will try at my best to sort your problem as early as possible.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home