473,399 Members | 3,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

writing hex to a binary file

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??
Nov 14 '05 #1
10 21394

On Thu, 22 Jan 2004, Caryn Graves wrote:

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
Nov 14 '05 #2
Caryn Graves wrote:
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.

Nov 14 '05 #3
On 22 Jan 2004 15:24:03 -0800, ca***@holonet.net (Caryn Graves) wrote
in comp.lang.c:
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.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #4
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> wrote in message news:<Pi***********************************@unix48 .andrew.cmu.edu>...
On Thu, 22 Jan 2004, Caryn Graves wrote:

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


Arthur, Mr. Tisdale- thanks to you both for replying to my post. I
posted to both the C and C++ groups because a solution in either
language would be O.K. in my case, and I was pretty desperate for
anything so I wanted to maximize my chances of getting some answer-
but anyway your C suggestions look just fine let's just stick to C...

So to generalize a bit: if say I wanted to output a value N that was
greater than 255, then I would use 2 of these hex characters, and how
about we put them in a character array and use fwrite as Mr. Tisdale
suggested:

char hexchars[2];
FILE *myfile = fopen("filename", "wb");
hexchar[0] = 0x<h1><h2>;
hexchar[1] = 0x<h3><h4>;
fwrite(hexchar, sizeof(char), 2, myfile);
fclose(myfile);

where N = (h1)*4096 + (h2)*256 + (h3)*16 + h4

And in my case N is not a constant that I would know ahead of time, so
I could just set up an array of these hex characters i.e.

unsigned char HEXES[16] = {0x00,0x01,0x02,0x03,0x04, ... etc.

and set each character in my hexchar array to the right element of
HEXES, according to the value of N.

Well if you see any blatant flaws in this please let me know (I
haven't had a chance to actually try this out yet, but I guess I'll
know for sure once I do code it up- I just didn't want to delay before
getting a reply out to you guys. I am really, truly grateful- this
seems to me like fairly basic stuff, and yet I was amazed at the hard
time I was having trying to come across it- like I couldn't find
anything along these lines in any of my C or C++ books- oh well...)
Nov 14 '05 #5
On 22 Jan 2004 15:24:03 -0800, ca***@holonet.net (Caryn Graves) wrote:
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??

Where are the values you want to write. Are they in variables? What
type of variables?

Taking the second case first, if the value you want to write will fit
in a char (a single byte by definition), then you can write the char
to a binary file with
char c = value;
fwrite(&c, sizeof c, 1, file_ptr);

If the value is larger than will fit in a char, do you have a type
that is the write size for the number of bytes you want to write?
(E.g., on some systems, a short int is two bytes.) If so, then
short s = value;
fwrite(&s, sizeof s, 1, file_ptr);

However, this is not portable. On another system, a short may be a
different size or be different endian. It is even possible that a
byte have more than 8 bits.

If you always want to write the value as two bytes big endian, which
is what you have in your example, try something like the following
unsigned char uc = -1;
int i = value;
unsigned char a[2];
a[0] = (unsigned)(i & (uc << CHAR_BIT)) >> CHAR_BIT;
a[1] = i & uc;
fwrite(a,sizeof a, 1, file_ptr);
<<Remove the del for email>>
Nov 14 '05 #6

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:40**************@jpl.nasa.gov...
Caryn Graves wrote:
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*.

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.
Use ostream member function write in C++ and fwrite in C.

Nov 14 '05 #7
Jumbo
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:40**************@jpl.nasa.gov...
Caryn Graves wrote:

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*.


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).

Nov 14 '05 #8
"Jumbo

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


Brian Rodenborn
Nov 14 '05 #9

On Fri, 23 Jan 2004, Caryn Graves wrote:

Arthur, Mr. Tisdale- thanks to you both for replying to my post. I
posted to both the C and C++ groups because a solution in either
language would be O.K. in my case, and I was pretty desperate for
anything so I wanted to maximize my chances of getting some answer-
[Don't worry about getting answers from comp.lang.c or comp.lang.c++;
we're desperate for questions to answer, here. ;) If you really
cared about the answers in *both* languages, it would have been
appropriate to post separate threads to both newsgroups, and if you
didn't care about both languages, you should have picked the one you
did care about right off the bat. Now that you've settled down to C,
it's all good. :-) ]
but anyway your C suggestions look just fine let's just stick to C...

So to generalize a bit: if say I wanted to output a value N that was
greater than 255, then I would use 2 of these hex characters, and how
about we put them in a character array and use fwrite as Mr. Tisdale
suggested:

char hexchars[2];
FILE *myfile = fopen("filename", "wb");
hexchar[0] = 0x<h1><h2>;
hexchar[1] = 0x<h3><h4>;
fwrite(hexchar, sizeof(char), 2, myfile);
fwrite(hexchar, 1, sizeof hexchar, myfile);

would be my preferred way to write it. Or using 2 in place of
'sizeof hexchar', possibly. But writing 'sizeof(char)' all the
time is redundant and confusing. Stick to the short and simple.
[sizeof(char)==1 by definition, since sizeof returns a number
of bytes, and 'char' is one byte wide by definition.]
fclose(myfile);

where N = (h1)*4096 + (h2)*256 + (h3)*16 + h4

And in my case N is not a constant that I would know ahead of time, so
I could just set up an array of these hex characters i.e.

unsigned char HEXES[16] = {0x00,0x01,0x02,0x03,0x04, ... etc.

and set each character in my hexchar array to the right element of
HEXES, according to the value of N.


Huh? You do realize that in your code above, HEXES[i] is exactly
equivalent to i, right? Was that just a vacuous example?

See the functions 'bwrite_endian' and 'fread_endian' in the
source code at
http://www.contrib.andrew.cmu.edu/~a...re/ImageFmtc.c
for a somewhat more modular way of writing integer values to
files, if that's what you're really trying to do. They're probably
over your head right now, and they probably assume 32-bit ints,
but they *might* help. Or not.

-Arthur

Nov 14 '05 #10
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> wrote in message news:<Pi***********************************@unix43 .andrew.cmu.edu>...
On Fri, 23 Jan 2004, Caryn Graves wrote:

Arthur, Mr. Tisdale- thanks to you both for replying to my post. I
posted to both the C and C++ groups because a solution in either
language would be O.K. in my case, and I was pretty desperate for
anything so I wanted to maximize my chances of getting some answer-
[Don't worry about getting answers from comp.lang.c or comp.lang.c++;
we're desperate for questions to answer, here. ;) If you really
cared about the answers in *both* languages, it would have been
appropriate to post separate threads to both newsgroups, and if you
didn't care about both languages, you should have picked the one you
did care about right off the bat. Now that you've settled down to C,
it's all good. :-) ]


My apologies- lesson learned. I don't post to these groups much, so I
was unaware of the protocol. I now know for the future, though.
but anyway your C suggestions look just fine let's just stick to C...

So to generalize a bit: if say I wanted to output a value N that was
greater than 255, then I would use 2 of these hex characters, and how
about we put them in a character array and use fwrite as Mr. Tisdale
suggested:

char hexchars[2];
FILE *myfile = fopen("filename", "wb");
hexchar[0] = 0x<h1><h2>;
hexchar[1] = 0x<h3><h4>;
fwrite(hexchar, sizeof(char), 2, myfile);
fwrite(hexchar, 1, sizeof hexchar, myfile);

would be my preferred way to write it. Or using 2 in place of
'sizeof hexchar', possibly. But writing 'sizeof(char)' all the
time is redundant and confusing. Stick to the short and simple.
[sizeof(char)==1 by definition, since sizeof returns a number
of bytes, and 'char' is one byte wide by definition.]


Ah, I see- another good point: everyone knows that a char is 1 byte,
but what's "2"? That does sort of stick out like a "magic number",
the way I had it.
fclose(myfile);

where N = (h1)*4096 + (h2)*256 + (h3)*16 + h4

And in my case N is not a constant that I would know ahead of time, so
I could just set up an array of these hex characters i.e.

unsigned char HEXES[16] = {0x00,0x01,0x02,0x03,0x04, ... etc.

and set each character in my hexchar array to the right element of
HEXES, according to the value of N.


Huh? You do realize that in your code above, HEXES[i] is exactly
equivalent to i, right? Was that just a vacuous example?


Well, actually I was thinking that HEXES[i] and i were not equivalent,
in the sense that the following code, (which I wrote up right after I
read your remarks above about my HEXES array, that caused me to doubt
my prior assumption), i.e.-

char test1[2], test2[2];
test1[0] = 0;
test1[1] = 168;
test2[0] = 0x00;
test2[1] = 0xA8;
FILE *fp1 = fopen("test1.out", "wb");
FILE *fp2 = fopen("test2.out", "wb");
fwrite(test1, 1, sizeof(test1), fp1);
fwrite(test2, 1, sizeof(test2), fp2);
fclose(fp1);
fclose(fp2);

would yield 2 files which were different- but after compiling and
running the above code I discovered that the contents of test1.out and
test2.out turned out to be exactly identical. So thus, if you just
replace the 2 lines

hexchar[0] = 0x<h1><h2>;
hexchar[1] = 0x<h3><h4>;

from the code in my previous post, with simply

hexchar[0] = h1*16 + h2;
hexchar[1] = h3*16 + h4;

and forget the HEXES array (which actually needed to be 256 long, not
16- but we're nixing it anyway so it doesn't really matter anymore),
then that does exactly what I was aiming for- and in fact I have at
this point put this in the actual code that I needed this for, tried
it out, and it did give me the desired results (to also settle the
controversy over what the "OP" meant- further apologies for not being
clearer with stating what I was seeking to accomplish.) Sincerest
thanks to all who took the time to offer their assistance! The OP is
happy now- and a bit more enlightened and less confused. :)
Nov 14 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
5
by: rob | last post by:
hey every1, I've got alot of data to write out to file and it's all just 1's and 0's. It's all stored in 2 dimensional arrays of width 32 and varying height. At the moment it's all just...
2
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start...
5
by: Neo | last post by:
Hello: I am receiving a Binary File in a Request from a application. The stream which comes to me has the boundary (Something like "---------------------------39<WBR>­0C0F3E0099" without the...
4
by: Greg | last post by:
Using the HttpWebRequest I'm downloading a PDF file and am trying to save it to the hard drive, but it keeps ending up corrupt (according to adobe acrobat). I know the PDF file isn't corrupt...
68
by: vim | last post by:
hello everybody Plz tell the differance between binary file and ascii file............... Thanks in advance vim
2
by: Thomi Aurel RUAG A | last post by:
Hy I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17). My Goal is to write a list of bytes down to a file (opened in binary mode) in one cycle. The crux is that a '0x0a' (line...
9
by: Ron Eggler | last post by:
Hi, I would like to write binary data in a file i open (ofstream) with ios::binary but it keeps failing and it gives me a segmentation fault. What I'm exactly doing: if (isBinary == true) {...
5
by: zehra.mb | last post by:
Hi, I had written application for storing employee data in binary file and reading those data from binary file and display it in C language. But I face some issue with writing data to binary file....
12
by: freeseif | last post by:
Hi programmers, I want read line by line a Unicode (UTF-8) text file created by Notepad, i don't want display the Unicode string in the screen, i want just read and compare the strings!. This...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.