cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : Integer Conversions
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Articles
Lounge
Jobs

-

question  Integer Conversions

Mayflower (25)
I have a question, but first...

1
2
3
4
5
6
bitmap.width = (int)//whatever number you like!

out << (bitmap.width      );
out << (bitmap.width >>  8);
out << (bitmap.width >> 16);
out << (bitmap.width >> 24);


Okay, I put this integer into the file correctly, but I am having a bit of trouble GETTING IT OUT!

Can anyone finish this?:
1
2
3
4
5
char meas[4];
in.get(meas[0]);  //All 4 bytes I put in
in.get(meas[1]);
in.get(meas[2]);
in.get(meas[3]);


Got anything?

PS-I posted what I thought was an answer on another post but after I looked into it, I found it was HORRIBLY wrong, please disregard my advice!
|
Duoas (1456)
No, you aren't outputting it correctly. You are writing four ints, each with an oddball value.

You need to be careful to write just one byte.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// write little-endian 4-byte integer
// MAKE SURE stream is opened in BINARY mode!
void write_int_le4( ostream& outs, int value )
  {
  for (int n = 0; n < 4; n++, value >>= 8)
    outs.put( (unsigned char)value );
  }

// read little-endian 4-byte integer
// MAKE SURE stream is opened in BINARY mode!
int read_int_le4( istream& ins )
  {
  int result = 0;
  unsigned char c;
  for (int n = 0; n < 4; n++)
    {
    ins.get( c );
    result = (result << 8) + c;
    }
  return result;
  }

Hope this helps.
|
Mayflower (25)
Umm, is there any known reason why ifstream can't ready unsigned chars? It's says it can't convert char & to unsigned char...
| Last edited on
Duoas (1456)
Argh. It is complaining about my cast on line 6. Just get rid of the (unsigned char) part and it should work fine.

Sorry.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us