From: "Damian Yerrick" Newsgroups: comp.os.msdos.djgpp Subject: Re: From Bytes to Int and Char Date: Sun, 15 Aug 1999 20:36:53 -0500 Organization: Rose-Hulman Institute of Technology Lines: 52 Message-ID: <7p7q0m$adb$1@solomon.cs.rose-hulman.edu> References: <37B466D7 DOT 958F09E5 AT americasm01 DOT nt DOT com> NNTP-Posting-Host: 137.112.204.250 X-Trace: solomon.cs.rose-hulman.edu 934767446 10667 137.112.204.250 (16 Aug 1999 01:37:26 GMT) X-Complaints-To: news AT cs DOT rose-hulman DOT edu NNTP-Posting-Date: 16 Aug 1999 01:37:26 GMT X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.00.2314.1300 X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2314.1300 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Campbell, Rolf [SKY:1U32:EXCH] wrote in message news:37B466D7 DOT 958F09E5 AT americasm01 DOT nt DOT com... > Nick wrote: > > > I am trying to load some data from a files, the 6 and 7th bytes are an > > Integer and so are the 11th and 12th. How do I make them into an INT? This > > is what I used earlier > > > > 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); > > -- > -Rolf Campbell (39)3-6318 > /* That still isn't byte-order safe. The byte-order-safe way to do it is by shifting each individual byte. The following code works on all platforms, but make sure that file_buffer points to _unsigned_ char data or you'll get nasty sign extension that screws this up. */ /* if file was written in big endian (Motorola-order) format */ sz = ((short)file_buffer[6] << 8) + file_buffer[7]; /* if file was written in little endian (Intel-order) format */ sz = ((short)file_buffer[7] << 8) + file_buffer[6]; /* Oh, by the way, the same kind of trick can be used to read 4-byte ints (on 16-bit platforms such as real mode DOS, change int to long) */ /* if file was written in big endian (Motorola-order) format */ score = ((int)file_buffer[16] << 24) + ((int)file_buffer[17] << 16) + ((int)file_buffer[18] << 8) + file_buffer[19]; /* if file was written in little endian (Intel-order) format */ score = ((int)file_buffer[19] << 24) + ((int)file_buffer[18] << 16) + ((int)file_buffer[17] << 8) + file_buffer[16]; This should clear things up. Damian Yerrick (comp DOT os DOT msdos DOT djgpp AT pineight DOT 8m DOT com) Download DOSArena from http://come.to/yerrick