コード例 #1
0
ファイル: mySort.c プロジェクト: kyon0304/backup_Learn
int Compare(void* a, void* b, int width)
{
//	return *( (int*)a ) > *( (int*)b ) ? 1 : 0;
	if(endian() == 1)
	{
		int count = 0;
		while(count < width)//little endian
		{
			if(*((char*)a+count) == *((char*)b+count))
				count++;
			else
				break;
		}
		return *((char*)a+count) > *((char*)b+count) ? 1 : 0;
	}
	else if(endian() == 2)
	{
		int count = width;
		while(count > 0)
		{
			if( *((char*)a+count) == *((char*)b+count)  )
				count--;
			else
				break;
		}
		return *((char*)a+count) > *((char*)b+count) ? 1 : 0;
	}
}
コード例 #2
0
ファイル: idxIO.cpp プロジェクト: 2php/eblearn
idxdim read_matrix_header(FILE *fp, int &magic) {
  int ndim, v, magic_vincent;
  int ndim_min = 3; // std header requires at least 3 dims even empty ones.
  idxdim dims;

  // read magic number
  if (fread(&magic, sizeof (int), 1, fp) != 1) {
    fclose(fp);
    eblthrow("cannot read magic number");
  }
  magic_vincent = endian(magic);
  magic_vincent &= ~0xF; // magic contained in higher bits

  // read number of dimensions
  if (is_magic(magic)) { // regular magic number, read next number
    if (fread(&ndim, sizeof (int), 1, fp) != 1) {
      fclose(fp);
      eblthrow("cannot read number of dimensions");
    }
    // check number is valid
    if (ndim > MAXDIMS) {
      fclose(fp);
      eblthrow("too many dimensions: " << ndim << " (MAXDIMS = "
               << MAXDIMS << ").");
    }
  } else if (is_magic_vincent(magic_vincent)) { // vincent magic number
    // ndim is contained in lower bits of the magic number
    ndim = endian(magic) & 0xF;
    ndim_min = ndim;
    magic = magic_vincent;
  } else { // unkown magic
    fclose(fp);
    eblthrow("unknown magic number: " << reinterpret_cast<void*>(magic)
             << " or " << magic << " vincent: " << magic_vincent);
  }
  // read each dimension
  for (int i = 0; (i < ndim) || (i < ndim_min); ++i) {
    if (fread(&v, sizeof (int), 1, fp) != 1) {
      fclose(fp);
      eblthrow("failed to read matrix dimensions");
    }
    // if vincent, convert to endian first
    if (is_magic_vincent(magic_vincent))
      v = endian(v);
    if (i < ndim) { // ndim may be less than ndim_min
      if (v <= 0) { // check that dimension is valid
        fclose(fp);
        eblthrow("dimension is negative or zero");
      }
      dims.insert_dim(i, v); // insert dimension
    }
  }
  return dims;
}
コード例 #3
0
ファイル: af_format.c プロジェクト: kax4/mpv
// Filter data through filter
static struct mp_audio* play(struct af_instance* af, struct mp_audio* data)
{
  struct mp_audio*   l   = af->data;	// Local data
  struct mp_audio*   c   = data;	// Current working data
  int 	       len = c->len/c->bps; // Length in samples of current audio block

  if(AF_OK != RESIZE_LOCAL_BUFFER(af,data))
    return NULL;

  // Change to cpu native endian format
  if((c->format&AF_FORMAT_END_MASK)!=AF_FORMAT_NE)
    endian(c->audio,c->audio,len,c->bps);

  // Conversion table
  if((c->format & AF_FORMAT_POINT_MASK) == AF_FORMAT_F) {
      float2int(c->audio, l->audio, len, l->bps);
      if((l->format&AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
	si2us(l->audio,len,l->bps);
  } else {
    // Input must be int

    // Change signed/unsigned
    if((c->format&AF_FORMAT_SIGN_MASK) != (l->format&AF_FORMAT_SIGN_MASK)){
      si2us(c->audio,len,c->bps);
    }
    // Convert to special formats
    switch(l->format&AF_FORMAT_POINT_MASK){
    case(AF_FORMAT_F):
      int2float(c->audio, l->audio, len, c->bps);
      break;
    default:
      // Change the number of bits
      if(c->bps != l->bps)
	change_bps(c->audio,l->audio,len,c->bps,l->bps);
      else
	memcpy(l->audio,c->audio,len*c->bps);
      break;
    }
  }

  // Switch from cpu native endian to the correct endianness
  if((l->format&AF_FORMAT_END_MASK)!=AF_FORMAT_NE)
    endian(l->audio,l->audio,len,l->bps);

  // Set output data
  c->audio  = l->audio;
  c->len    = len*l->bps;
  c->bps    = l->bps;
  c->format = l->format;
  return c;
}
コード例 #4
0
ファイル: endian.c プロジェクト: imbyungjun/TIL
int main() {
	int cases;

	scanf("%d", &cases);

	while (cases--)
		endian();
}
コード例 #5
0
ファイル: ptr2.c プロジェクト: copley/C_Programming_Training
int main(int argc, char* argv[])
{
	int value;
	value = endian();
	if (value == 1) 
		printf("The machine is Little endian %d\n",value); 
	else									
		printf("The machine is Big Endian %d\n",value); 
	return 0;
}
コード例 #6
0
ファイル: endian.c プロジェクト: JeonHanSem/TIL
int main(){
	int t;
	unsigned int num;

	scanf("%d",&t);

	while(t--){
		scanf("%u",&num);
		printf("%u\n",endian(num));
	}
}
コード例 #7
0
ファイル: xiv_readers.cpp プロジェクト: socam/xiv
// Read a ppm image, returns 0 if not recognized.
// Returns width, height, nb of bytes (1 or 2) and max value for 16 bits imagery.
// Max value is used in case a 16 bits image has less significant bits (eg 12 or 14 for some camera).
unsigned char* read_ppm(const char* sFile, int& iW, int& iH, int& nbBytes, int& max)
{
  FILE *f = fopen(sFile,"rb");
  if(f==NULL)
    return 0;
  char sTmp[1024];
  // P6
  read_ppm_line(f,sTmp);
  if(strstr(sTmp,"P6")!=sTmp)
    {
      fclose(f);
      return 0;
    }
  // iW, iH
  read_ppm_line(f,sTmp);
  sscanf(sTmp,"%d %d",&iW,&iH);
  if(iW<0 || iW>65536 || iH<0 || iH > 65536)
    {
      fclose(f);
      return 0;
    }
  // 255
  read_ppm_line(f,sTmp);
  if(strstr(sTmp,"255")==sTmp)
    {
      nbBytes=1;
      max=255;
    }
  else if (strstr(sTmp,"65535")==sTmp)
    {
      nbBytes=2;
      max=0;// Will be computed later
    }
  else
    return 0;
  unsigned char* buf = (unsigned char*)malloc(iW*iH*3*nbBytes);
  if(buf==NULL) return 0;

  fread(buf,iW*iH,3*nbBytes,f);
  // If image is 16 bit wide, compute max value in case there a less significant bytes.
  if(nbBytes==2)
    {
      unsigned short* p=(unsigned short*)buf;
      for(int i=0;i<iW*iH*3;i++)
	{
	  if(endian())
	    *p=swap(*p);
	  if(*p>max) max=*p;
	  p++;
	}
    }
  fclose(f);
  return buf;
}
コード例 #8
0
ファイル: Msu2rsf.c プロジェクト: 1014511134/src
int
main (int argc, char *argv[])
{
  const bool su = true;
  bool verb, xdr;
  char *filename, *trace;
  int format=0, ns, ntr, itrace[SF_NKEYS];
  off_t pos, nsegy;
  float dt;
  FILE *file;
  extern int fseeko (FILE * stream, off_t offset, int whence);

/**** Start common code with segy2rsf (16 lines) ****/
  sf_init (argc, argv);

  if (!sf_getbool ("verb", &verb))
    verb = false;
  /* Verbosity flag */

  if (!sf_getbool ("endian", &xdr))
    xdr = true;
  /* Whether to automatically estimate endianness or not */
  if (xdr)
    endian ();

  if (NULL == (filename = sf_getstring ("tape")))	/* input data */
    sf_error ("Need to specify tape=");

  if (NULL == (file = fopen (filename, "rb")))
    sf_error ("Cannot open \"%s\" for reading:", filename);

  pos = readfilesize (file);
/**** End common code with segy2rsf ****/

  /* Figure out ns and ntr */

  trace = sf_charalloc (SF_HDRBYTES);
  if (SF_HDRBYTES != fread (trace, 1, SF_HDRBYTES, file))
    sf_error ("Error reading first trace header");
  fseeko (file, 0, SEEK_SET);

  segy2head (trace, itrace, SF_NKEYS);
  ns = itrace[segykey ("ns")];
  dt = itrace[segykey ("dt")] / 1000000.;
  free (trace);

  nsegy = SF_HDRBYTES + ns * 4;
  ntr = pos / nsegy;

  su_or_segy_to_rsf (verb, su, ntr, format, ns, itrace, nsegy, file, dt);

  exit (0);
}
コード例 #9
0
ファイル: endianCheck.c プロジェクト: bearxiong99/new_swamm
int main(void)
{
    static long int str[2] = { 0x41424344,0x0 }; /* ASCII "ABCD" */

    printf("if your machine does print : \n");
    printf("        DCBA = little-endian ( VAX, PC )\n");
    printf("        ABCD =    big-endian ( MC6800, Sun4, HP9000/715 )\n");
    printf("        BADC =    PDP-endian ( PDP-11 )\n\n");
    printf("your machine gives : ''%s'', so it is a ''%s'' one\n", (char *) str, endian());

	return 0;
}
コード例 #10
0
ファイル: struct.c プロジェクト: liyana/liyana.github.com
int main(int argc, const char *argv[])
{
 
if(endian())
printf("%s\n","yes");
else
printf("%s\n","no");
//  printf("%d\n",x1.b[i]);
   //z1.ccc.a=2;
//printf("%f\n",z1.ccc.a);
return 0;
}
コード例 #11
0
ファイル: util.cpp プロジェクト: LittoCats/libnode
String::CPtr percentEncode(String::CPtr str, String::Encoding enc) {
    static const Boolean isBigEndian = endian() == BIG;

    if (!str || str->length() == 0)
        return String::create();

    Buffer::Ptr buf;
    switch (enc) {
    case String::UTF8:
        buf = Buffer::create(str, Buffer::UTF8);
        break;
    case String::UTF16:
        if (isBigEndian) {
            buf = Buffer::create(str, Buffer::UTF16BE);
        } else {
            buf = Buffer::create(str, Buffer::UTF16LE);
        }
        break;
    case String::UTF16BE:
        buf = Buffer::create(str, Buffer::UTF16BE);
        break;
    case String::UTF16LE:
        buf = Buffer::create(str, Buffer::UTF16LE);
        break;
    case String::UTF32:
        if (isBigEndian) {
            buf = Buffer::create(str, Buffer::UTF32BE);
        } else {
            buf = Buffer::create(str, Buffer::UTF32LE);
        }
        break;
    case String::UTF32BE:
        buf = Buffer::create(str, Buffer::UTF32BE);
        break;
    case String::UTF32LE:
        buf = Buffer::create(str, Buffer::UTF32LE);
        break;
    default:
        assert(false);
        buf = Buffer::null();
    }
    Size sourceLen = buf->length();
    const char* source = static_cast<const char*>(buf->data());
    Size encodedLen = sourceLen * 3 + 1;
    char* encoded = new char[encodedLen];
    percentEncode(encoded, encodedLen, source, sourceLen);
    String::CPtr res = String::create(encoded);
    delete[] encoded;
    return res;
}
コード例 #12
0
ファイル: psrxml_unpackers.c プロジェクト: SixByNine/psrxml
void unpackDataChunk_32bit(unsigned char* raw, float* outdata, int nbits,
        int nchans, unsigned int nsamps, enum endianness end, char isSigned,
        char isChannelInterleaved, int nsampStart, int nsampEnd,
        char swapChannels) {
    int i, channel, sample;
    int in, out, outchan;
    char swapem = 0;
    float* farr = (float*) raw;

    if(end!=INDEPENDANT){
	    swapem = endian() != end;
    }
    if (!isChannelInterleaved) {
        for (channel = 0; channel < nchans; channel++) {
            if (swapChannels) {
                outchan = nchans - channel - 1;
            } else {
                outchan = channel;
            }
            in = channel*nsamps;
            out = outchan*nsamps;
            for (sample = nsampStart; sample < nsampEnd; sample++) {
                outdata[out + sample] = farr[in + sample];
                swap_bytes((unsigned int*) (&outdata[out + sample]), swapem);
            }
        }
    } else {
        farr += nsampStart * nchans;
        
        for (sample = nsampStart; sample < nsampEnd; sample++) {
            for (channel = 0; channel < nchans; channel++) {

                if (swapChannels) {
                    out = (nchans - channel - 1) * nsamps + sample;
                    outdata[out]
                            = *farr;
                } else {
                    out = (channel) * nsamps + sample;
                    outdata[out]
                            = *farr;
                }
                swap_bytes((unsigned int*) (&outdata[out]), swapem);
                farr++;

            }
        }
    }

}
コード例 #13
0
ファイル: af_convertsignendian.c プロジェクト: asdlei00/mpv
static int filter(struct af_instance *af, struct mp_audio *data, int flags)
{
    int infmt = data->format;
    int outfmt = af->data->format;
    size_t len = data->samples * data->nch;

    if ((infmt & AF_FORMAT_END_MASK) != (outfmt & AF_FORMAT_END_MASK))
        endian(data->planes[0], len, data->bps);

    if ((infmt & AF_FORMAT_SIGN_MASK) != (outfmt & AF_FORMAT_SIGN_MASK))
        si2us(data->planes[0], len, data->bps,
              (outfmt & AF_FORMAT_END_MASK) == AF_FORMAT_LE);

    mp_audio_set_format(data, outfmt);
    return 0;
}
コード例 #14
0
ファイル: af_format.c プロジェクト: benf/mpv
static struct mp_audio* play_swapendian(struct af_instance* af, struct mp_audio* data)
{
  struct mp_audio*   l   = af->data;	// Local data
  struct mp_audio*   c   = data;	// Current working data
  int 	       len = c->len/c->bps; // Length in samples of current audio block

  if(AF_OK != RESIZE_LOCAL_BUFFER(af,data))
    return NULL;

  endian(c->audio,l->audio,len,c->bps);

  c->audio = l->audio;
  mp_audio_set_format(c, l->format);

  return c;
}
コード例 #15
0
ファイル: af_format.c プロジェクト: divVerent/mplayer2
static af_data_t* play_swapendian(struct af_instance_s* af, af_data_t* data)
{
  af_data_t*   l   = af->data;	// Local data
  af_data_t*   c   = data;	// Current working data
  int 	       len = c->len/c->bps; // Length in samples of current audio block

  if(AF_OK != RESIZE_LOCAL_BUFFER(af,data))
    return NULL;

  endian(c->audio,l->audio,len,c->bps);

  c->audio = l->audio;
  c->format = l->format;

  return c;
}
コード例 #16
0
ファイル: readfile.c プロジェクト: OPENDAP/bes
void show_opt(void)
{
	fprintf(stderr,"\nOptions:\n");
	fprintf(stderr,"   %c:  text\t\tas ASCII, decimal, hexadecimal, and octal\n", TEXT_CODE);
	fprintf(stderr,"   %c:  int8\t\t1 byte signed integer\n", INT8_CODE);
	fprintf(stderr,"   %c:  int16\t\t2 byte signed integer\n", INT16_CODE);
	fprintf(stderr,"   %c:  int32\t\t4 byte signed integer\n", INT32_CODE);
#ifdef LONGS_ARE_64
	fprintf(stderr,"   %c:  int64\t\t8 byte signed integer\n", INT64_CODE);
#endif
	fprintf(stderr,"   %c:  float32\t\t4 byte single-precision floating point\n", FLOAT32_CODE);
	fprintf(stderr,"   %c:  float64\t\t8 byte double-precision floating point\n", FLOAT64_CODE);
	fprintf(stderr,"  %c%c:  uint8\t\t1 byte unsigned integer\n", UINT_PREFIX, INT8_CODE);
	fprintf(stderr,"  %c%c:  uint16\t\t2 byte unsigned integer\n", UINT_PREFIX, INT16_CODE);
	fprintf(stderr,"  %c%c:  uint32\t\t4 byte unsigned integer\n", UINT_PREFIX, INT32_CODE);
#ifdef LONGS_ARE_64
	fprintf(stderr,"  %c%c:  uint64\t\t8 byte unsigned integer\n", UINT_PREFIX, INT64_CODE);
#endif

	fprintf(stderr,"\n");
	fprintf(stderr,"   b:  Toggle between \"%s-endian\" and your machine's native byte order\n"
	        , endian() == LITTLE_ENDIAN ? "big" : "little");
	fprintf(stderr,"   p:  Set new file position\n");
	fprintf(stderr,"   P:  Show present file position and length\n");
	fprintf(stderr,"   h:  Display this help screen\n");
	fprintf(stderr,"   q:  Quit\n\n");
	fprintf(stderr,"%s option codes to view binary encoded values.\n"
#if FF_OS == FF_OS_DOS
          , "Type"
#endif
#if FF_OS == FF_OS_UNIX
          , "Enter"
#endif
	       );
	fprintf(stderr,"Tip:  %s return repeats the last option.\n"
#if FF_OS == FF_OS_DOS
          , "Pressing"
#endif
#if FF_OS == FF_OS_UNIX
          , "Entering a blank"
#endif
         );

	return;
}
コード例 #17
0
//          returns - 0 if the endian type read in is invalid
int CheckSystemEndian ()
{
  int endianness;
  
  endianness = endian();

  if (endianness == BIGENDIAN)
  {
    printf("\nThe endian of the system is big endian");
    return BIGENDIAN;
  }  // if statement
  else if (endianness == LITTLEENDIAN)
  {
    printf ("\nThe endian of the system is little endian");
    return LITTLEENDIAN;
  }  // else if statement
  else
    return 0;
}  // CheckSystemEndian
コード例 #18
0
ファイル: machine.c プロジェクト: pierric/Utils
int main(int argc, char *argv[])
{
	int ch;
	while((ch = getopt(argc, argv, "ife")) != -1) {
		switch(ch) {
		case 'i':
			integral();
			break;
		case 'f':
			fractional();
			break;
		case 'e':
			endian();
			break;
		default:
			exit(1);
		}
	}
}
コード例 #19
0
/* map addr to dst in network byte order, addr is in network byte order */
static void ip_map_addr(void *dst, struct in_addr *addr)
{
	char *ptr;
        char fill[] = "0xFFFF";

	ptr = (char *)dst;	/* needed for pointer arithmetic */
	if (endian() == BIG) {		/* put addr at back (big end) */
		bzero(ptr, INET6_ADDRLEN);
		ptr += INET6_ADDRLEN - (sizeof(fill) + sizeof(struct in_addr));
		memcpy(ptr, fill, sizeof(fill));
		ptr += sizeof(fill);
		memcpy(ptr, addr, sizeof(struct in_addr)); 		
	} else { /* put addr at front (little end) */
		bzero(ptr, INET6_ADDRLEN);
		memcpy(ptr, addr, sizeof(struct in_addr)); 		
		ptr += sizeof(struct in_addr);
		memcpy(ptr, fill, sizeof(fill));
		ptr += sizeof(fill);
	}
}
コード例 #20
0
ファイル: sat_recon.hpp プロジェクト: solium/hacklympics
    void lift_fog_of_war(std::FILE* xwd)
    {
        X11WINDOWDUMP head;
        std::fread(&head,sizeof(head),1,xwd);
        if(head.ByteOrder == 0)
        {
            head.HeaderSize = endian(head.HeaderSize);
            head.FileVersion = endian(head.FileVersion);
            head.PixmapFormat = endian(head.PixmapFormat);
            head.PixmapDepth = endian(head.PixmapDepth); 
            head.PixmapWidth = endian(head.PixmapWidth);
            head.PixmapHeight = endian(head.PixmapHeight);
            head.XOffset = endian(head.XOffset);    
            head.ByteOrder = endian(head.ByteOrder);  
            head.BitmapUnit = endian(head.BitmapUnit); 
            head.BitmapBitOrder = endian(head.BitmapBitOrder);
            head.BitmapPad = endian(head.BitmapPad);     
            head.BitsPerPixel = endian(head.BitsPerPixel);  
            head.BytesPerLine = endian(head.BytesPerLine);  
            head.VisualClass = endian(head.VisualClass);   
            head.RedMask = endian(head.RedMask);       
            head.GreenMask = endian(head.GreenMask);     
            head.BlueMask = endian(head.BlueMask);      
            head.BitsPerRgb = endian(head.BitsPerRgb);    
            head.NumberOfColors = endian(head.NumberOfColors); 
            head.ColorMapEntries = endian(head.ColorMapEntries);
            head.WindowWidth = endian(head.WindowWidth);    
            head.WindowHeight = endian(head.WindowHeight);   
            head.WindowX = endian(head.WindowX);        
            head.WindowY = endian(head.WindowY);        
            head.WindowBorderWidth = endian(head.WindowBorderWidth);
        }

        char junk[1024];
        int pad = head.HeaderSize - sizeof(head);
        if(pad > 0) 
        {
            std::fread(junk,pad,1,xwd);
        }

        std::vector<X11COLORMAP> map(head.ColorMapEntries);
        std::fread(&map[0],sizeof(X11COLORMAP),head.ColorMapEntries,xwd);
        for(int i=0;i<map.size();++i)
        {
            map[i].EntryNumber = endian(map[i].EntryNumber);
            map[i].Red = endian(map[i].Red);
            map[i].Green = endian(map[i].Green);
            map[i].Blue = endian(map[i].Blue);
            map[i].Flags = endian(map[i].Flags);
            map[i].Padding = endian(map[i].Padding);
        }

        this->width = head.PixmapWidth;
        this->height = head.PixmapHeight;
        this->pixels.resize(this->width * this->height);

        std::vector<char> buf(head.BytesPerLine);
        char* p = (char*)&(this->pixels[0]);
        for(int i=0;i<head.PixmapHeight;++i)
        {
            std::fread(&buf[0],1,head.BytesPerLine,xwd);
            char* b = &buf[0];
            for(int j=0;j<head.PixmapWidth;++j,b+=4)
            {
                *p++ = b[2];
                *p++ = b[1];
                *p++ = b[0];
            }
        }
    }
コード例 #21
0
globalDataValues* loadCvmDataAll(gridStruct *location, char *outputDirectory)
{
    
    // perform endian check
    int endianInt;
    endianInt = endian();
    
    globalDataValues *globDataVals;
    globDataVals = malloc(sizeof(globalDataValues));

    char veloModDir[128];
    sprintf(veloModDir,"%s/Velocity_Model",outputDirectory);
    
    FILE *fvp, *fvs, *frho;
    char vp3dfile[64];
    sprintf(vp3dfile,"%s/vp3dfile.p",veloModDir);
    
    char vs3dfile[64];
    sprintf(vs3dfile,"%s/vs3dfile.s",veloModDir);
    
    char rho3dfile[64];
    sprintf(rho3dfile,"%s/rho3dfile.d",veloModDir);
    
    float *vp, *vs, *rho;
    int bsize, ip;
    
    fvp = fopen(vp3dfile,"r");
    fvs = fopen(vs3dfile,"r");
    frho = fopen(rho3dfile,"r");
    
    bsize = location->nX*location->nZ*sizeof(float);
    vp = (float*) malloc(bsize);
    vs = (float*) malloc(bsize);
    rho = (float*) malloc(bsize);
    
    float vsRead, vpRead, rhoRead;
    
    printf("Reading binary files.\n");
    for(int iy = 0; iy < location->nY; iy++)
    {
        //increment a counter
//        printf("%d / %d complete \n",iy+1,location->nY);
        printf("\rReading velocity model from file %d%% complete.", iy*100/location->nY);
        fflush(stdout);
        
        //now read the obtained file in binary
        fread(vp,sizeof(vp[0]),location->nX*location->nZ,fvp);
        fread(vs,sizeof(vs[0]),location->nX*location->nZ,fvs);
        fread(rho,sizeof(rho[0]),location->nX*location->nZ,frho);
        for(int iz = 0; iz < location->nZ; iz++)
        {
            for (int ix = 0; ix < location->nX; ix++)
            {
                ip = ix + iz * location->nX;  //index counter
                vpRead = vp[ip];
                vsRead = vs[ip];
                rhoRead = rho[ip];

                if (endianInt == 1) // big endian, implement byteswap
                {
                    globDataVals->Vp[ix][iy][iz] = float_swap(vpRead);
                    globDataVals->Vs[ix][iy][iz] = float_swap(vsRead);
                    globDataVals->Rho[ix][iy][iz] = float_swap(rhoRead);
//                    printf("swappingRead\n");
                }
                else if (endianInt == 0) // system is little endain, read as is.
                {
                    globDataVals->Vp[ix][iy][iz] = vpRead;
                    globDataVals->Vs[ix][iy][iz] = vsRead;
                    globDataVals->Rho[ix][iy][iz] = rhoRead;
                }
            }
        }
    }
    printf("\rReading velocity model from file 100%% complete.");
    fflush(stdout);
    printf("\n");

    
    free(vp);
    free(vs);
    free(rho);
    fclose(fvp);
    fclose(fvs);
    fclose(frho);
    printf("Binary file read complete.\n");
    return globDataVals;
}
コード例 #22
0
ファイル: create_raw_index.c プロジェクト: sdelarquier/code
main()
{
long t1, told, rec_offset;
long indrec[2];
short int indata[8192];
int rind_file;
RAW_FILE *raw_file;
size_t iostat;
struct rawdata *raddat;
short int etst;
long int ltemp;
int i;

char raw_name[80], rind_name[80], filename[80];

raddat = (struct rawdata *) calloc(1, sizeof(struct rawdata));

rec_offset = 0;		/* initialize the byte number */
told = 0;

printf("Ready to create an index file to the raw RADOPS 386 radar data\n");
printf("\nEnter the file name (no extension) of the raw data file: ");
scanf("%s",raw_name);
getchar();	/* get rid of the <cr> at the end */

strcpy(filename,raw_name);
strcat(rind_name,raw_name);

if ((raw_file = rawropen(filename)) == 0)
	{
	printf("Unable to open raw data file\n");
	exit(ENOENT);
	}

/* Now open the index file for output */

strcat(rind_name,".rin");
rind_file = open(rind_name,O_RDWR|O_CREAT|O_TRUNC,0664);
if(rind_file <= 0) 
	{
	printf("Unable to open output file %s, fp=%x\n",rind_name,rind_file);
	exit(ENOENT);	
	}
else 
{
    printf("The index file will be created in the current directory\n");
}

/*	now start reading the raw data file and filing in the index */

while (1)
	{
	rec_offset = raw_file->raw_offset;
	iostat = raw_read(raw_file, 0, raddat);
	if (iostat == EOF)
		{
		close(rind_file);
		raw_close(raw_file);
		exit(0);
		}
	t1 = cnv_mdhms_sec(&(raddat->PARMS.YEAR),
			&(raddat->PARMS.MONTH),
			&(raddat->PARMS.DAY),
			&(raddat->PARMS.HOUR),
			&(raddat->PARMS.MINUT),
			&(raddat->PARMS.SEC));
	indrec[0]=t1;
	indrec[1]=rec_offset;
	
	if (endian(&etst) == 0) {
	  for (i=0; i < 2; ++i) {
	    ltemp = indrec[i];
	    swab_dword(&indrec[i],&ltemp);
	  }
	}
	write(rind_file, indrec, sizeof(indrec[0])*2);
	if (t1-told > 900)
		{
		printf("%d  %d\n",t1,rec_offset);
		told = t1;
		}
	}
}
コード例 #23
0
CModelFile* CModelReader::read()
{
    atUint32 magic = base::readUint32();

    if (magic != 0xDEADBABE)
    {
        Athena::io::MemoryWriter tmp;
        decompressFile(tmp, base::data(), base::length());

        if (tmp.length() > 0x10)
            base::setData(tmp.data(), tmp.length());

        magic = base::readUint32();
    }

    if (magic != 0xDEADBABE /*&& magic != 0x9381000A*/)
        THROW_INVALID_DATA_EXCEPTION("Not a valid CMDL magic, expected 0xDEADBABE got 0x%.8X\n", magic);
    atUint32 version;
    if (magic != 0x9381000A)
        version = base::readUint32();
    else
        version = CModelFile::DKCR;

    if (!(version >= CModelFile::MetroidPrime1 && version <= CModelFile::DKCR))
        THROW_INVALID_DATA_EXCEPTION("Only Metroid Prime 1 to 3 models are supported got v%i\n", version);

    try
    {
        m_result = new CModelFile;
        m_result->m_version = (CModelFile::Version)version;
        m_result->m_flags = base::readUint32();
        m_result->m_boundingBox.min.x = base::readFloat();
        m_result->m_boundingBox.min.y = base::readFloat();
        m_result->m_boundingBox.min.z = base::readFloat();
        m_result->m_boundingBox.max.x = base::readFloat();
        m_result->m_boundingBox.max.y = base::readFloat();
        m_result->m_boundingBox.max.z = base::readFloat();

        atUint32 sectionCount = base::readUint32();
        atInt32 materialCount = base::readInt32();

        m_sectionSizes.resize(sectionCount);

        if (m_result->m_flags & 0x10)
        {
            base::readUint32();
            atUint32 visGroupCount = base::readUint32();
            while((visGroupCount--) > 0)
            {
                atUint32 len = base::readUint32();
                base::readString(len);
            }

            base::readUint32();
            base::readUint32();
            base::readUint32();
            base::readUint32();
            base::readUint32();
        }

        m_result->m_materialSets.resize(materialCount);
        for (atUint32 i = 0; i < sectionCount; i++)
            m_sectionSizes[i] = base::readUint32();

        base::seekAlign32();

        const atUint32 sectionBias = ((m_result->m_version == CModelFile::DKCR || m_result->m_version == CModelFile::MetroidPrime3)
                                      ? 1 : materialCount);

        Athena::io::MemoryReader sectionReader(new atUint8[2], 2);
        sectionReader.setEndian(endian());
        for (atUint32 i = 0; i < sectionCount; i++)
        {
            if (m_sectionSizes[i] == 0)
                continue;

            if (materialCount > 0)
            {
                if (m_result->m_version != CModelFile::DKCR && m_result->m_version != CModelFile::MetroidPrime3)
                {
                    atUint8* data = base::readUBytes(m_sectionSizes[i]);
                    CMaterialReader reader(data, m_sectionSizes[i]);
                    CMaterialSet materialSet;
                    switch(m_result->m_version)
                    {
                        case CModelFile::MetroidPrime1:
                            materialSet = reader.read(CMaterial::MetroidPrime1);
                            break;
                        case CModelFile::MetroidPrime2:
                            materialSet = reader.read(CMaterial::MetroidPrime2);
                            break;
                        default:
                            break;
                    }

                    m_result->m_materialSets[i] = materialSet;
                    materialCount--;
                    continue;
                }
                else
                {
                    atUint8* data = base::readUBytes(m_sectionSizes[i]);
                    CMaterialReader reader(data, m_sectionSizes[i]);
                    atUint32 setIdx = 0;
                    while ((materialCount--) > 0)
                    {
                        CMaterialSet& materialSet = m_result->m_materialSets[setIdx];
                        switch(m_result->m_version)
                        {
                            case CModelFile::MetroidPrime3:
                                materialSet = reader.read(CMaterial::MetroidPrime3);
                                break;
                            case CModelFile::DKCR:
                                materialSet = reader.read(CMaterial::DKCR);
                            default:
                                break;
                        }
                        setIdx++;
                    }
                    continue;
                }
            }
            else
            {
                SectionType section = (SectionType)(i - sectionBias);
                atUint8* data = base::readUBytes(m_sectionSizes[i]);
                sectionReader.setData(data, m_sectionSizes[i]);
                switch(section)
                {
                    case SectionType::Vertices:
                    {
                        if (m_result->m_flags & 0x20)
                            readVertices(sectionReader, true);
                        else
                            readVertices(sectionReader);
                    }
                        break;
                    case SectionType::Normals:
                        readNormals(sectionReader);
                        break;
                    case SectionType::Colors:
                        readColors(sectionReader);
                        break;
                    case SectionType::TexCoord0:
                        readTexCoords(0, sectionReader);
                        break;
                    case SectionType::TexCoord1orMeshOffsets:
                    {
                        if (m_result->m_flags & EFormatFlags::TexCoord1 || m_result->m_version == CModelFile::DKCR)
                            readTexCoords(1, sectionReader);
                        else
                            readMeshOffsets(sectionReader);
                        break;
                    }
                    case SectionType::MeshInfo:
                    {
                        if (m_meshOffsets.size() == 0)
                        {
                            readMeshOffsets(sectionReader);
                            break;
                        }
                    }
                    default:
                        if ((i - sectionBias) >= 5)
                            readMesh(sectionReader);
                        break;
                }
            }
        }
    }
    catch(...)
    {
        delete m_result;
        m_result = nullptr;
        throw;
    }

    return m_result;
}
コード例 #24
0
ファイル: idxIO.cpp プロジェクト: 2php/eblearn
bool has_multiple_matrices(const char *filename) {
  // open file
  FILE *fp = fopen(filename, "rb");
  if (!fp)
    return false;
  // read header
  int magic;
  idxdim d;
  try { d = read_matrix_header(fp, magic); }
  catch(ebl::eblexception &e) { return false; }
  int magic_vincent = endian(magic);
  magic_vincent &= ~0xF; // magic contained in higher bits
  intg size = d.nelements();
  // compute data size
  switch (magic) {
    case MAGIC_BYTE_MATRIX:
    case MAGIC_UBYTE_VINCENT:
      size *= sizeof (ubyte);
      break ;
    case MAGIC_INTEGER_MATRIX:
    case MAGIC_INT_VINCENT:
      size *= sizeof (int);
      break ;
    case MAGIC_FLOAT_MATRIX:
    case MAGIC_FLOAT_VINCENT:
      size *= sizeof (float);
      break ;
    case MAGIC_DOUBLE_MATRIX:
    case MAGIC_DOUBLE_VINCENT:
      size *= sizeof (double);
      break ;
    case MAGIC_LONG_MATRIX:
      size *= sizeof (long);
      break ;
    case MAGIC_UINT_MATRIX:
      size *= sizeof (uint);
      break ;
    case MAGIC_UINT64_MATRIX:
      size *= sizeof (uint64);
      break ;
    case MAGIC_INT64_MATRIX:
      size *= sizeof (int64);
      break ;
    default:
      eblerror("unknown magic number: " << reinterpret_cast<void*>(magic)
             << " or " << magic << " vincent: " << magic_vincent);
  }
  // go to end of data
  fseek(fp, size, SEEK_CUR);
  fpos_t pos;
  fgetpos(fp, &pos);
  // now go to end of file
  fseek(fp, 0, SEEK_END);
  fpos_t endpos;
  fgetpos(fp, &endpos);
  fclose(fp);
  // compare
#if defined(__WINDOWS__) || defined(__MAC__) || defined(__ANDROID__)
  if (pos != endpos)
#else
    if (pos.__pos != endpos.__pos)
#endif
      return true;
  return false;
}
コード例 #25
0
inline endian endian_check(int x = 1){return endian(*reinterpret_cast<char*>(&x));}
コード例 #26
0
static void 
rbv_readData(int nlhs, mxArray *plhs[])
{  
  double *outData;          /* the return data of the matlab matrix as double array  */
  int outDataPos;           /* the number of data blocks written to the outData  */
  int rawDataPos;			      /* the number of data blocks read from the file  */
  int outDataSize;          /* the number of blocks in the outdata  */
  bool swap;                /* swap the bytes of the data */
  
  double *dataBlock;        /* one data block we will read from the file */
  short  *readBuffer;       /* a temporary array we will actually read to */
  double selectedChannelValue; /* one value from the eeg data */
  int selectedChannel, n;
  
  swap = rawDataEndian != endian();
  dataBlock = malloc(rawDataChannelCount * sizeof(double));
  readBuffer = malloc(rawDataChannelCount * sizeof(short));
  
  /* construct the data output matrix. */
  outDataSize = rawDataPoints / firFilterSize; 
  
  if(fileStart == -1) {
    fileStart = 0;
  }
  if(fileEnd == -1) {
    fileEnd = outDataSize;
  }
  
  if(dataPtr == 0) {
    plhs[0] = mxCreateDoubleMatrix(outDataSize, optChannelSelectCount, mxREAL);
    outData = mxGetPr(plhs[0]);
  } else {
    outData = dataPtr;
    outDataSize = dataPtrSize;
  }
  outDataPos = 0;
  
  
  for(rawDataPos = 0; rawDataPos < rawDataPoints; ++rawDataPos) {
   rbv_readDataBlock(dataBlock,readBuffer, rawDataChannelCount,swap);
   for(n = 0; n < optChannelSelectCount;++n) {
     selectedChannel = (int)optChannelSelect[n];
     selectedChannelValue = dataBlock[selectedChannel]; /* get the value */
     selectedChannelValue *= rawDataScale[selectedChannel]; /* scal the value */
     
     selectedChannelValue = rbv_filterDataIIR(selectedChannelValue, n); /* IIR Filter */
     firFilterValues[n] += selectedChannelValue; /* fir Filter */
   }
   
   /* update the count of the values in the fir filter */
   firFilterPosition++;

   /* flush the fir filter and write to outData */
   if(firFilterPosition == firFilterSize) {
     firFilterPosition = 0;

     for(n = 0;n < optChannelSelectCount; ++n) {
       if(fileStart <= outDataPos && 
          outDataPos <= fileEnd &&  /*we only set the data when we are in the range*/
          dataEnd >= outDataPos + dataStart - fileStart) { /* check for the bounds of the data*/
        outData[n * outDataSize + outDataPos + dataStart - fileStart] = firFilterValues[n] / firFilterSum;
       }
       firFilterValues[n] = 0;
     }
     outDataPos++;
  }

   /* update the postition of the latest data in the IIR filter */
   --iirFilterOffset;
   if( iirFilterOffset < 0) {
     iirFilterOffset = iirFilterSize - 1;
   }
  }
    
  free(dataBlock);
  free(readBuffer);
}
コード例 #27
0
ファイル: EngrdaWidget.cpp プロジェクト: Siddharthk/opticks
void EngrdaWidget::updateData(QTreeWidgetItem* pItem)
{
   if (pItem != NULL && pItem->childCount() == 0)
   {
      mpValueType->setEnabled(true);
      mpDataUnits->setEnabled(true);
      mpData->setEnabled(true);
      DynamicObject* pDo = reinterpret_cast<DynamicObject*>(qvariant_cast<void*>(pItem->data(0, Qt::UserRole)));
      try
      {
         if (pDo != NULL)
         {
            Endian endian(BIG_ENDIAN_ORDER);
            unsigned int cols = dv_cast<unsigned int>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGMTXC));
            unsigned int rows = dv_cast<unsigned int>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGMTXR));
            std::string type = dv_cast<std::string>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGTYP));
            std::string units = dv_cast<std::string>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGDATU));
            unsigned int dts = dv_cast<unsigned int>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGDTS));
            if (dts == 0)
            {
               return;
            }
            const std::vector<unsigned char>& data = dv_cast<Blob>(pDo->getAttribute(Nitf::TRE::ENGRDA::ENGDATA));
            if (data.empty())
            {
               return;
            }
            const void* pData = reinterpret_cast<const void*>(&data.front());

            mpValueType->setText(QString("%1 byte %2").arg(dts).arg(QString::fromStdString(type)));
            mpDataUnits->setText(QString::fromStdString(units));
            mpData->setColumnCount(cols);
            mpData->setRowCount(rows);

            bool isAscii = false;
            EncodingType encoding;
            if (type == "S" && dts == 1)
            {
               encoding = INT1SBYTE;
            }
            else if (type == "S" && dts == 2)
            {
               encoding = INT1SBYTE;
            }
            else if (type == "S" && dts == 2)
            {
               encoding = INT2SBYTES;
            }
            else if (type == "S" && dts == 4)
            {
               encoding = INT4SBYTES;
            }
            else if (type == "R" && dts == 4)
            {
               encoding = FLT4BYTES;
            }
            else if (type == "R" && dts == 8)
            {
               encoding = FLT8BYTES;
            }
            else if (type == "C" && dts == 8)
            {
               encoding = FLT8COMPLEX;
            }
            else if (type == "I" && dts == 1)
            {
               encoding = INT1UBYTE;
            }
            else if (type == "I" && dts == 2)
            {
               encoding = INT2UBYTES;
            }
            else if (type == "I" && dts == 4)
            {
               encoding = INT4UBYTES;
            }
            else if (type == "A")
            {
               isAscii = true;
               if (dts != 1)
               {
                  return;
               }
            }
            unsigned int datc  = data.size() / dts;
            if ((!encoding.isValid() && !isAscii) || datc != (rows * cols))
            {
               mpData->setEnabled(false);
               return;
            }
            for (size_t row = 0; row < rows ; ++row)
            {
               for (size_t col = 0; col < cols; ++col)
               {
                  if (isAscii)
                  {
                     // Not tested due to lack of test data
                     size_t idx = col + (row * cols); // datc chars per item
                     const QByteArray buf(reinterpret_cast<const char*>(pData) + idx, 1);
                     QTableWidgetItem* pItem = new QTableWidgetItem(QString(buf));
                     mpData->setItem(row, col, pItem);
                  }
                  else if (encoding == FLT8COMPLEX)
                  {
                     // Complex hasn't been tested due to lack of test data
                     //
                     size_t idx = (col * 2) + (row * cols * 2); // 2 floats per item
                     double real = std::numeric_limits<double>::quiet_NaN();
                     switchOnEncoding(FLT4BYTES, getDataValue, pData, idx, real, endian);
                     idx++;
                     double imag = std::numeric_limits<double>::quiet_NaN();
                     switchOnEncoding(FLT4BYTES, getDataValue, pData, idx, imag, endian);
                     QTableWidgetItem* pItem = new QTableWidgetItem(
                        QString::number(real, 'g', 12) + ", " + QString::number(imag, 'g', 12));
                     mpData->setItem(row, col, pItem);
                  }
                  else
                  {
                     size_t idx = col + row * cols;
                     double val = std::numeric_limits<double>::quiet_NaN();
                     switchOnEncoding(encoding, getDataValue, pData, idx, val, endian);
                     QTableWidgetItem* pItem = new QTableWidgetItem(QString::number(val, 'g', 12));
                     mpData->setItem(row, col, pItem);
                  }
               }
            }
         }
         return;
      }
      catch(const std::bad_cast&)
      {
      }
   }

   mpValueType->setText(QString());
   mpDataUnits->setText(QString());
   mpData->clear();
   mpValueType->setEnabled(false);
   mpDataUnits->setEnabled(false);
   mpData->setEnabled(false);
}
コード例 #28
0
ファイル: concat.c プロジェクト: srkaeppler/code
main(int argc, void *argv[])
{
    DIR *dirp;
    struct dirent *thedir;
    char dirname[100];
    int fp1,fp2,fp3,compare();
    char day_string[6];
    char filename[100];
    char fitfile[100];
    char inxfile[100];
    char froot[20];
    char *file_list[100];
    char *rad;
    short i,j,fcount,first;
    long start_t,end_t,start_r,end_r;
    long rec_num,nrec,xcf,rec_t,two;
    int endi, etst;
    size_t stlen;
    unsigned int buf_size;
    union BUF
    {
        char buf[FIT_RECL];
        union FIT_REC fit_rec;
    } fit_buf;
    union INX_BUF
    {
        char buf[INX_RECL];
        struct INX_HDR inx_hdr;
        struct INX_INDEX inx_rec;
    } inx_buf;

    if (argc <= 2)
    {
        printf( "Use:\n");
        printf( "concat dir day_string radar\n");
        printf( "or\n");
        printf( "concat file_list\n");
        exit( 0);
    }

    bzero( dirname, 100);
    bzero( day_string, 6);
    bzero( filename, 100);
    bzero( fitfile, 100);
    bzero( inxfile, 100);
    bzero( froot, 20);

    endi= endian( &etst);

    two = 2;
    rad = (char *)argv[3];
    if( ((argc > 3) && (strlen(rad) > 1)) || (argc <= 3))
    {
        for( j=1; j<=argc-1; j++ )
        {
            file_list[j-1] = (char *)argv[j];
        }
        strcpy(dirname,".");
        fcount = j;
    } else {
        strcpy(dirname,(char *)argv[1]);
        strncpy(day_string,(char *)argv[2],6);
        if( (dirp = opendir(dirname)) == NULL )
        {
            fprintf(stderr,"ERROR--COULD NOT OPEN DIRECTORY\n");
        }
        j=0;
        while( (thedir = readdir(dirp)) != NULL)
        {
            if((strstr(thedir->d_name,day_string) != NULL) &&
                    ((strpbrk(thedir->d_name,rad) - thedir->d_name)< 10) &&
                    (strpbrk(thedir->d_name,rad) != NULL) &&
                    (strstr(thedir->d_name,"fit") != NULL) &&
                    (strpbrk(thedir->d_name,"C") == NULL))
            {
                file_list[j] = (char *) malloc( strlen(thedir->d_name)+1 );
                strcpy(file_list[j],thedir->d_name);
                j ++;
            }
        }
        fcount = j+1;
    }
    qsort(file_list,fcount-1,sizeof(char *), compare);
    /* Mod to four digit years; 20000111 DA */
    strncpy(froot,file_list[0], 11);
    strcat(strcpy(fitfile,froot),"C.fit");
    strcat(strcpy(inxfile,froot),"C.inx");
    printf("New File: %s\n",fitfile);
    fflush(stdout);
    if((fp2=open(fitfile, O_WRONLY | O_CREAT, S_IRUSR |
                 S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) == -1)
    {
        fprintf(stderr,"ERROR--COULD NOT OPEN FILE %s\n",fitfile);
        exit(0);
    }
    if((fp3=open(inxfile, O_WRONLY | O_CREAT, S_IRUSR |
                 S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) == -1)
    {
        fprintf(stderr,"ERROR--COULD NOT OPEN FILE %s\n",inxfile);
        exit(0);
    }
    strcpy(filename,dirname);
    strcat(filename,"/");
    strcat(filename,file_list[0]);
    if((fp1=open(filename,O_RDONLY)) == -1)
    {
        fprintf(stderr,"ERROR--COULD NOT OPEN FILE %s\n",filename);
        exit(0);
    }
    read(fp1,fit_buf.buf,FIT_RECL);
    write(fp2,fit_buf.buf,FIT_RECL);
    write(fp3,inx_buf.buf,INX_RECL);
    rec_num=2;
    start_t = 0;
    end_r = 0;
    first = 1;
    nrec = 0;
    for( i=1; i<fcount; i++ )
    {
        printf("FILE:  %s\n",filename);
        while( read(fp1,fit_buf.buf,FIT_RECL) == FIT_RECL )
        {
            if( fit_buf.fit_rec.v13_r0.rtime != 0 )
            {
                write(fp2,fit_buf.buf,FIT_RECL);
                if( fit_buf.fit_rec.v13_r0.rrn == 0 && first != 1 )
                {
                    if (endi == 0)
                    {
                        swab_dword(&inx_buf.inx_rec.rtime,&rec_t);
                        swab_dword(&inx_buf.inx_rec.recno,&rec_num);
                        swab_dword(&inx_buf.inx_rec.nrec,&nrec);
                        swab_dword(&inx_buf.inx_rec.xflag,&xcf);
                    }
                    write(fp3,inx_buf.buf,INX_RECL);
                    if (endi == 0)
                    {
                        swab_dword(&rec_t,&fit_buf.fit_rec.v13_r0.rtime);
                    }
                    rec_num += nrec;
                    xcf = fit_buf.fit_rec.v13_r0.r_parm.XCF;
                    nrec = 0;
                    end_r ++;
                } else if( first == 1 ) {
                    fflush(stdout);
                    first = 0;
                    if (endi == 0)
                    {
                        swab_dword(&start_t,&fit_buf.fit_rec.v13_r0.rtime);
                    }
                    rec_t = start_t;
                    fflush(stdout);
                }
                nrec++;
            }
        }
        close(fp1);
        if ( i < (fcount - 1) )
        {
            strcpy(filename,dirname);
            strcat(filename,"/");
            strcat(filename,file_list[i]);
            if((fp1=open(filename,O_RDONLY)) == -1)
            {
                fprintf(stderr,"ERROR--COULD NOT OPEN FILE %s\n",filename);
            }
            read(fp1,fit_buf.buf,FIT_RECL);
        }
    }
    if (endi == 0)
    {
        swab_dword(&inx_buf.inx_rec.rtime,&rec_t);
        swab_dword(&inx_buf.inx_rec.recno,&rec_num);
        swab_dword(&inx_buf.inx_rec.nrec,&nrec);
        swab_dword(&inx_buf.inx_rec.xflag,&xcf);
    }
    write(fp3,inx_buf.buf,INX_RECL);
    if (endi == 0)
    {
        swab_dword(&inx_buf.inx_hdr.stime,&start_t);
        swab_dword(&inx_buf.inx_hdr.etime,&rec_t);
        swab_dword(&inx_buf.inx_hdr.srec,&two);
        swab_dword(&inx_buf.inx_hdr.erec,&end_r);
    }
    lseek(fp3,0,SEEK_SET);
    write(fp3,inx_buf.buf,INX_RECL);
    close(fp2);
    close(fp3);
}
コード例 #29
0
ファイル: audiotool.cpp プロジェクト: tws67/bayonne-cygwin
int main(int argc, char **argv)
#endif
{
	char *cp;

	if(argc < 2) {
		cerr << "use: audiotool --option [args...]" << endl;
		exit(-1);
	}
	++argv;
	cp = *argv;
	if(!strncmp(cp, "--", 2))
		++cp;

#ifdef	W32
	SetConsoleCtrlHandler(down, TRUE);
#else
	signal(SIGINT, down);
	signal(SIGTERM, down);
	signal(SIGQUIT, down);
	signal(SIGABRT, down);
#endif

	if(!stricmp(cp, "-version"))
		version();
	else if(!stricmp(cp, "-modpath") || !stricmp(cp, "-path"))
		libpath();
	else if(!stricmp(cp, "-endian"))
		endian();
	else if(!stricmp(cp, "-soundcard"))
	{
		if(*(++argv))
			soundcard(atoi(*argv));
		else
			soundcard(0);
	}
#ifdef	CODEC_MODFLAGS
	else if(!stricmp(cp, "-modflags"))
		modflags();
#endif
#ifdef	AUDIO_LIBRARY
	else if(!stricmp(cp, "-ldflags"))
		ldflags();
#endif
	else if(!stricmp(cp, "-info"))
		Tool::info(++argv);
	else if(!stricmp(cp, "-size"))
		Tool::size(++argv);
	else if(!stricmp(cp, "-notation") || !stricmp(cp, "-annotation"))
		Tool::notation(++argv);
	else if(!stricmp(cp, "-chart"))
		Tool::chart(++argv);
	else if(!stricmp(cp, "-strip"))
		Tool::strip(++argv);
	else if(!stricmp(cp, "-trim"))
		Tool::trim(++argv);
	else if(!stricmp(cp, "-build"))
		Tool::build(++argv);
	else if(!stricmp(cp, "-append"))
		Tool::append(++argv);
	else if(!stricmp(cp, "-play"))
		Tool::play(++argv);
	else if(!stricmp(cp, "-packets"))
		Tool::packetdump(++argv);

	cerr << "audiotool: " << *argv << ": unknown option" << endl;
	exit(-1);
}
コード例 #30
0
ファイル: xiv_readers.cpp プロジェクト: socam/xiv
// Read a ppm image, returns 0 if not recognized.
// Returns width, height, nb of bytes (1 or 2) and max value for 16 bits imagery.
// Max value is used in case a 16 bits image has less significant bits (eg 12 or 14 for some camera).
unsigned char* read_tiff(const char* file, int& iW, int& iH, int& nbBytes, int& max)
{
#ifdef HAVE_LIBTIFF
  // reject NEF files which could be recognized as TIFF
  if(strlen(file)>=3 && strcasecmp(file+strlen(file)-3,"nef")==0)
    return 0;
  TIFF* tif = TIFFOpen(file, "r");
  if (tif) 
    {
      TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &iW);
      TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &iH);
      uint16_t c=0xFFFF,bs=8,fo=1,rs=1,tw=1,tl=1,ph=0,es=0;
      uint16_t * esv;
      TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &c);
      TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bs);
      TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rs);
      TIFFGetField(tif, TIFFTAG_FILLORDER,&fo);
      TIFFGetField(tif, TIFFTAG_TILEWIDTH,& tw);
      TIFFGetField(tif, TIFFTAG_TILELENGTH,& tl);
      TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &ph);
      TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &es, &esv);
      if(verbose) fprintf(stderr,"read_tiff %s w %d h %d #c %d bps %d fo %d tile %d %d photo %d es %d\n",file,iW,iH,c,bs,fo,tw,tl,ph,es);
      if(c==0xFFFF) // Try to guess number of chanels
	{
	  if(ph==PHOTOMETRIC_MINISBLACK)
	    {
	      c=1;
	    }
	  else if (ph==PHOTOMETRIC_RGB)
	    {
	      c=3;
	    }
	  else
	    {
	      TIFFClose(tif);
	      return 0;
	    }
	  c+=es;
	}

      if(fo==2 || tw != 1 || tl != 1 || (ph!=PHOTOMETRIC_MINISBLACK && ph!=PHOTOMETRIC_RGB) ) // Don't handle odd fill order or tiled tiff
	{
	  TIFFClose(tif);
	  return 0;
	}
      if(bs==16) // 16b images, compute maxi in case it has less significant bits.
	{nbBytes=2; max=0;}
      else if(bs==8) {nbBytes=1; max=255;} // 8 bit image, set maxi to 255
      else // Only handle 16b or 8b images
	{
	  TIFFClose(tif);
	  return 0;
	}
      
      tdata_t bufstrip;
      bufstrip = _TIFFmalloc(TIFFStripSize(tif));
      if(bufstrip==NULL)
	{
	  TIFFClose(tif);
	  return 0;
	}
      unsigned char* buf = (unsigned char*)malloc(iW*iH*3*nbBytes);
      if(buf==NULL)
	{
	  _TIFFfree(bufstrip);
	  TIFFClose(tif);
	  return 0;
	}
      
      int row=0;
      for (unsigned int strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
	{
	  TIFFReadEncodedStrip(tif, strip, bufstrip, (tsize_t) -1);
	  if(nbBytes==1) // Case of standard 8 bits images
	    {
	      unsigned char* p=(unsigned char*)bufstrip;
	      for(int rowS=0;rowS<rs&&row<iH;rowS++)
		{
		  for(int col=0;col<iW;col++)
		    {
		      // 3 channels or more (alpha) use only the first 3 ones
		      if(c>=3)
			{
			  for(int cha=0;cha<3;cha++)
			    {
			      buf[3*(row*iW+col)+cha] = p[c*(col+rowS*iW)+cha];
			    }
			}
		      else
			{
			  buf[3*(row*iW+col)+0] = buf[3*(row*iW+col)+1] = buf[3*(row*iW+col)+2] = p[rowS*iW+col];
			}
		    }
		  row++;
		}
	    }
	  else if(nbBytes==2) // Case of 16 bits imagery
	    {
	      unsigned short* p=(unsigned short*)bufstrip;
	      unsigned short* b=(unsigned short*)buf;
	      for(int rowS=0;rowS<rs&&row<iH;rowS++)
		{
		  for(int col=0;col<iW;col++)
		    {
		      // 3 channels or more (alpha) use only the first 3 ones
		      if(c>=3)
			{
			  for(int cha=0;cha<3;cha++)
			    {
			      if (endian())
				b[3*(row*iW+col)+cha] = p[c*(col+rowS*iW)+cha];
			      else
				b[3*(row*iW+col)+cha] = swap(p[c*(col+rowS*iW)+cha]);
			      
			      if(b[3*(row*iW+col)+cha]>max) max=b[3*(row*iW+col)+cha];
			    }
			}
		      else // Convert Gray -> RGB
			{
			  if (endian())
			    b[3*(row*iW+col)+0] = b[3*(row*iW+col)+1] = b[3*(row*iW+col)+2] = p[rowS*iW+col];
			  else
			    b[3*(row*iW+col)+0] = b[3*(row*iW+col)+1] = b[3*(row*iW+col)+2] = swap(p[rowS*iW+col]);
			  if(b[3*(row*iW+col)+0]>max) max=b[3*(row*iW+col)+0];
			}
		    }
		  row++;
		}
	    }
	}
      _TIFFfree(bufstrip);

      TIFFClose(tif);
      return buf;
    }
#endif
  return 0;
}