From: ryot AT bigfoot DOT com (George Ryot) Newsgroups: comp.os.msdos.djgpp Subject: Re: From Bytes to Int and Char Message-ID: <37ba82f5.7514501@news.clara.net> References: <37B466D7 DOT 958F09E5 AT americasm01 DOT nt DOT com> <37B4DFD1 DOT 4D66 AT surfsouth DOT com> <37B57EB0 DOT 492A93AE AT unb DOT ca> X-Newsreader: Forte Agent 1.5/32.452 X-No-Archive: yes MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Date: Sat, 14 Aug 1999 14:54:48 GMT NNTP-Posting-Host: 195.8.92.239 X-Complaints-To: abuse AT clara DOT net X-Trace: nnrp3.clara.net 934642488 195.8.92.239 (Sat, 14 Aug 1999 15:54:48 BST) NNTP-Posting-Date: Sat, 14 Aug 1999 15:54:48 BST Lines: 49 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Endlisnis wrote: > Chris Holmes wrote: > > > > > char ver, type; > > > > int sz, tz; > > > > sz = file_buffer[6] + file_buffer[7]; > > > > is that right? > > > > > > No. Here's the right way to do it. This code is not edian safe. > > > sz = *(short*)(file_buffer+6); > > > > (sorry... have to say it) They aren't endians, they're native > > arrangements. Please, be PC with your PC. > > I don't know what you are talking about. The word endian means the native > order of bytes in a multibyte contiguous variable type. > > > One solution (kinda tricky because you need to make sure they are > > stored on a 2 byte boundary or hack around my trick, which is a hack > > itself). > > Given: void *buffer; > > make: char *c_buffer=(char *)buffer; > > make: short *i_buffer=(short *)buffer; > > then: short i = i_buffer[BYTE_OFFSET / 2]; > > (this should be a little more endian safe) > > I don't see how, because it's doing the exact same thing in a more obsure way. > I was trying to say that if the file was stored on a big-endian machine, then using > a little-endian like DJGPP to read the file in the way I mentioned wouldn't work. Me thinks some programmers just get stuck in hack mode determined to produce unsafe code for the sake of a few microseconds. ;-)) How would Nick extract the byte pairs he needs using that last hack? The following (boring?) solution should do the trick: unsigned short sz, tz; sz = (file_buffer[5] << 8) & file_buffer[6]; tz = (file_buffer[10] << 8) & file_buffer[11]; Note that I have assumed you really do mean 6th, 7th, 11th & 12th bytes (file_buffer[0] would be the first byte) and that the 16-bit integers are stored high byte low byte. I have also assumed that the values are unsigned (always positive), things might get complicated otherwise. You can use int instead of short if you prefer. -- george