Printing in hex

Hi!
I'm composing the header for a wav file, and I need to insert the filesize. I have used
1
2
fseek (input_pointer , 0 , SEEK_END);  // 
long source_size = ftell(input_pointer);    // Obtain the length of the file  

to find the filesize.

I need to insert the filesize into the header in the format shown below

EG 96,000 is 0x017700 so written as 0077 0100 (in hex viewer).

How do I do this? I can't find the correct formats to go from the int32 to... whatever is necessary.

[edit] using fprintf...

One further exmaple. If the value was 192,000 it would need to be written such that it appeared as 00ee 0200 in a hex viewer.

thanks,
Paul
Last edited on
Is that space in the middle necessary? If it is, you'll need to implement you own dec to hex conversion. Either that or insert it yourself in the buffer.
Last edited on
thank you for your reply.
no, the space isn't necessary, it's just the way it copied and pasted from my hex viewer.
it's worth noting that i don't actually need to write anything in hex, but the hex viewer i am using is only to help understand the way the characters have been rearranged.
Oh, I see. Your question is why the order of the bytes changed, then?
no, not why, but how do i do it
Don't have much time, but here's a quick bet:

Put your number in a string stream, create a string from it, get bytes from it and output them to file in reverse order. Would that work?

1
2
3
4
5
6
7
8
9
10
stringstream ss;
string s;
string bytes[4];
ofstream headerfile
// Open file etc.
ss << hex << setfixed(8) << filesize;
s = ss.str();

for(int i=0; i<4; i++)  bytes[i] = s(s.begin()+2*i, s.begin()+2*(i+1));
for(int i=3; i<=0; i--)  headerfile << bytes[i];


Remember to #include iomanip. I'm not sure of it, but something along these lines should work...
Last edited on
You need invert the endianness of the integer.
For example, suppose you wanted to invert the endianness of a 16-bit integer:
1
2
int16 x=?;
int16 y=(x<<8)|(x>>8);

For more bits, you will need to do some bit twiddling. Just remember that (0x12345678 & 0x0000FF00)==0x00005600.
Topic archived. No new replies allowed.