writing hex to a binary file

C

Caryn Graves

I need to write hex into a binary file, i.e., '00A8' (decimal 168)
output as 2 bytes, 'FE' (decimal 254) output as 1 byte, etc.
Suggestions??
 
A

Arthur J. O'Dwyer

I need to write hex into a binary file, i.e., '00A8' (decimal 168)
output as 2 bytes, 'FE' (decimal 254) output as 1 byte, etc.
Suggestions??

Don't cross-post between groups for unrelated languages unless
you're prepared for a lot of useless information that doesn't
apply to your language of choice. For instance, this is how
you'd do it in C, but the preferred C++ way is subtly different
(e.g., at least using <cstdio>, if not some clever <iostream>
manipulation).
Followups set to comp.lang.c on this subthread.

#include <stdio.h>

int main(void)
{
FILE *myfile = fopen("filename", "wb");
putc(0x00, myfile);
putc(0xA8, myfile);
putc(0xFE, myfile);
fclose(myfile);
return 0;
}

HTH,
-Arthur
 
E

E. Robert Tisdale

Caryn said:
I need to write hex into a binary file, i.e., '00A8' (decimal 168)
output as 2 bytes, 'FE' (decimal 254) output as 1 byte, etc.

You are confused.
You want to write *binary*.

Use ostream member function write in C++ and fwrite in C.
 
J

Jack Klein

I need to write hex into a binary file, i.e., '00A8' (decimal 168)
output as 2 bytes, 'FE' (decimal 254) output as 1 byte, etc.
Suggestions??

Suggestion 1: Don't cross-post between comp.lang.c and comp.lang.c++.

Suggestion 2: Clarify your question. Hexadecimal is a concept of
text, not of pure binary files.
 
J

Jumbo

E. Robert Tisdale said:
You are confused.
You want to write *binary*.
Yes this is exactly the case.
I think what OP means though is when the file is opened it will display the
data as hex.
So this would really be down to the way you display it rather that the way
it is written to the file.
 
E

E. Robert Tisdale

Jumbo
Yes this is exactly the case.
I think what OP means though is when the file is opened
it will display the data as hex.
So this would really be down to the way you display it
rather that the way it is written to the file.

To "display" "00A8" on an ASCII terminal requires 4 bytes -- not 2.
To "display" "FE" on an ASCII terminal requires 2 bytes -- not 1.

The OP *must* mean the *binary* representation
of integers 0x00A8 (168) and 0xFE (254).
 
D

Default User

"Jumbo

Oh great, now I have to killfile this moron in CLC too. Damn these
cross-posts.




Brian Rodenborn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top