static void flipBytesFor64Bits(char* p) { swapBytes(p, p + 7); swapBytes(p + 1, p + 6); swapBytes(p + 2, p + 5); swapBytes(p + 3, p + 4); }
// fills in fields of the provided udp_header from the buffer, starting at the offset void readUdpHeader(uint8_t* buff, udp_header_t* udp_header, uint32_t current_offset) { extractData((uint8_t*)&udp_header->source_port, current_offset + udp_source_port_offset, buff, int16_len); udp_header->source_port = swapBytes(udp_header->source_port); extractData((uint8_t*)&udp_header->dest_port, current_offset + udp_dest_port_offset, buff, int16_len); udp_header->dest_port = swapBytes(udp_header->dest_port); extractData((uint8_t*)&udp_header->total_length, current_offset + udp_total_length_offset, buff, int16_len); udp_header->total_length = swapBytes(udp_header->total_length); extractData((uint8_t*)&udp_header->checksum, current_offset + udp_checksum_offset, buff, int16_len); }
/*----------------------------------------------------------------------------*/ void sendViaUDP(ethernet_frame_t* eth) { uint16_t udp_len = udp_header_length + eth->message.length; eth->udp_header.source_port = swapBytes(PORT); eth->udp_header.dest_port = swapBytes(PORT); eth->udp_header.total_length = swapBytes(udp_len); eth->udp_header.checksum = 0; sendViaIP(eth); }
std::shared_ptr<Buffer> Element::encode(bool notobject) { // GNASH_REPORT_FUNCTION; size_t size = 0; std::shared_ptr<Buffer> buf; if (_type == Element::OBJECT_AMF0) { // Calculate the total size of the output buffer // needed to hold the encoded properties if (_name) { size = getNameSize() + AMF_HEADER_SIZE; } for (size_t i=0; i<_properties.size(); i++) { size += _properties[i]->getDataSize(); size += _properties[i]->getNameSize(); size += AMF_PROP_HEADER_SIZE; } gnash::log_debug(_("Size of Element \"%s\" is: %d"), _name, size); buf.reset(new Buffer(size+AMF_PROP_HEADER_SIZE)); if (!notobject) { *buf = Element::OBJECT_AMF0; } if (_name > static_cast<char *>(nullptr)) { size_t length = getNameSize(); std::uint16_t enclength = length; swapBytes(&enclength, 2); *buf += enclength; string str = _name; *buf += str; std::uint8_t byte = static_cast<std::uint8_t>(0x5); *buf += byte; } for (size_t i=0; i<_properties.size(); i++) { std::shared_ptr<Buffer> partial = AMF::encodeElement(_properties[i]); // log_debug("Encoded partial size for is %d", partial->size()); // _properties[i]->dump(); // partial->dump(); if (partial) { *buf += partial; partial.reset(); } else { break; } } // log_debug("FIXME: Terminating object"); if (!notobject) { std::uint8_t pad = 0; *buf += pad; *buf += pad; *buf += TERMINATOR; } return buf; } else { return AMF::encodeElement(*this); } return buf; }
void writeSETHeader(FILE *fp, uint32_t num_objects, endianness_t endianness) { if (endianness == SET_BIG_ENDIAN) { // Convert to big endian uint8_t *ptr = (uint8_t*)&num_objects; swapBytes(ptr, ptr + 3); swapBytes(ptr + 1, ptr + 2); } fwrite(&num_objects, 4, 1, fp); int i; for (i=0; i<28; i++) { uint8_t zero = 0; fwrite(&zero, 1, 1, fp); } }
void read_band(int b) { /** We'll read a block of pm.height() rows of our image. */ asf::pixel_rectangle pm=out->pixel_meta_bounds(); log(11," Reading band %d: rows %d to %d to zoom %d\n", b,pm.lo_y,pm.hi_y-1,out->pixel().zoom()); /* Seek to the start of our piece of image data */ fseek(f,bytes_band*b+bytes_row*pm.lo_y,SEEK_SET); /* Read image data rows */ readbuf.resize(bytes_row*pm.height()); if (1!=fread(&readbuf[0],readbuf.size(),1,f)) asf::die("I/O error reading image "+(std::string)*filename); /* Convert image data format during copy to out */ asf::pixel_rectangle p=out->pixels(); for (int y=p.lo_y;y<p.hi_y;y++) { unsigned char *row=&readbuf[y*bytes_row+p.lo_x*bytes_pixel]; if (ddr.needs_swap) swapBytes(row,(p.hi_x-p.lo_x),bytes_pixel); for (int x=p.lo_x;x<p.hi_x;x++) { float v=0.0; switch (ddr.dtype) { case DTYPE_BYTE: v=*(unsigned char *)row; break; case DTYPE_SHORT: v=*(short *)row; break; case DTYPE_LONG: v=*(int *)row; break; case DTYPE_FLOAT: v=*(float *)row; break; case DTYPE_DOUBLE:v=*(double *)row; break; }; out->at(x,y,b)=v; row+=bytes_pixel; } } }
uint32_t readSETHeader(FILE *fp, endianness_t endianness) { // Returns number of objects. uint32_t objects; fread(&objects, 4, 1, fp); fseek(fp, 32, SEEK_SET); if (endianness == SET_BIG_ENDIAN) { // Convert to little endian uint8_t *ptr = (uint8_t*)&objects; swapBytes(ptr, ptr + 3); swapBytes(ptr + 1, ptr + 2); } // Return 0 if EOF already. return feof(fp) ? 0 : objects; }
int CCP4File::readBinValueasInt_(char* data, Position pos) { int int_value = *((int*)(data + 4*pos)); if (swap_bytes_) swapBytes(int_value); return int_value; }
float CCP4File::readBinValueasFloat_(char* data, Position pos) { float float_value = *((float*)(data + 4*pos)); if (swap_bytes_) swapBytes(float_value); return float_value; }
short int DSN6File::readHeaderValue_(char* header, Position pos) throw() { short int val = *((short int*)(header + 2*pos)); if (swap_bytes_) swapBytes(val); return val; }
/*----------------------------------------------------------------------------*/ void sendViaIP(ethernet_frame_t* eth) { uint8_t temp_header[ip_header_length]; uint16_t ip_len = ip_header_length + swapBytes(eth->udp_header.total_length); // must swap bytes again eth->ip_header.version_and_header_len = 0x45; eth->ip_header.service_type = 0; eth->ip_header.total_len = swapBytes(ip_len); eth->ip_header.indication = 0; eth->ip_header.flags_and_fragment_offset = 0; eth->ip_header.time_to_live = 255; eth->ip_header.protocol = udp_protocol_num; eth->ip_header.header_checksum = 0; eth->ip_header.source_address = myip; eth->ip_header.dest_address = dom0ip; // generate IP checksum using temporary storage array writeIPHeader(temp_header, ð->ip_header, 0); eth->ip_header.header_checksum = cksum((uint16_t*)temp_header, ip_header_length); sendViaEth(eth); }
double TextureInterpolator::sample( double ss, double tt ) { double val = 0.0; if( !_valid || _validZerro || !_data.data) { return val; } ELEV_TYPE *data = (ELEV_TYPE*)_data.data->data(); // To flip t int flipT = 255; double s = ss; double t = tt; unsigned int ts = globeConfig::instance()->getTileSpan(); double _s = (ts - 2 ) * ((s * _tscale) + _soff); double _t = (ts - 2 ) * ((t * _tscale) + _toff); unsigned int s0 = (unsigned int)_s; unsigned int s1 = s0 < (ts - 1) ? s0 + 1 : s0; double ds = _s - double(s0); unsigned int t0 = (unsigned int) flipT-_t; unsigned int t1 = t0 < (ts - 1) ? t0 + 1 : t0; _vScale = 1.0; double dt = flipT-_t - double(t0); double v00 = (double)(swapBytes(data[t0 * ts + s0])) * _vScale; double v01 = (double)(swapBytes(data[t0 * ts + s1])) * _vScale; double v10 = (double)(swapBytes(data[t1 * ts + s0])) * _vScale; double v11 = (double)(swapBytes(data[t1 * ts + s1])) * _vScale; double vv0 = v00 * (1.0-ds) + v01 * ds; double vv1 = v10 * (1.0-ds) + v11 * ds; val = vv0 * (1.0-dt) + vv1 * dt; return val; }
// fills in fields of the provided ip_header from the buffer, starting at the offset void readIPHeader(uint8_t* buff, ip_header_t* ip_header, uint32_t current_offset) { extractData((uint8_t*)&ip_header->version_and_header_len, current_offset + ip_version_and_header_len_offset, buff, int8_len); extractData((uint8_t*)&ip_header->service_type, current_offset + ip_service_type_offset, buff, int8_len); extractData((uint8_t*)&ip_header->total_len, current_offset + ip_total_len_offset, buff, int16_len); ip_header->total_len = swapBytes(ip_header->total_len); extractData((uint8_t*)&ip_header->indication, current_offset + ip_indication_offset, buff, int16_len); extractData((uint8_t*)&ip_header->flags_and_fragment_offset, current_offset + ip_flags_and_fragment_offset_offset, buff, int16_len); extractData((uint8_t*)&ip_header->time_to_live, current_offset + ip_time_to_live_offset, buff, int8_len); extractData((uint8_t*)&ip_header->protocol, current_offset + ip_protocol_offset, buff, int8_len); extractData((uint8_t*)&ip_header->header_checksum, current_offset + ip_header_checksum_offset, buff, int16_len); extractData((uint8_t*)&ip_header->source_address, current_offset + ip_source_address_offset, buff, int32_len); extractData((uint8_t*)&ip_header->dest_address, current_offset + ip_dest_address_offset, buff, int32_len); }
static bool EnterMuuid(const char *p, MUUID &result) { if (*p++ != '{') return false; BYTE *d = (BYTE*)&result; for (int nBytes = 0; *p && nBytes < 24; p++) { if (*p == '-') continue; if (*p == '}') break; if (!isxdigit(*p)) return false; if (!isxdigit(p[1])) return false; int c = 0; if (sscanf(p, "%2x", &c) != 1) return false; *d++ = (BYTE)c; nBytes++; p++; } if (*p != '}') return false; swapBytes(&result.a, sizeof(result.a)); swapBytes(&result.b, sizeof(result.b)); swapBytes(&result.c, sizeof(result.c)); return true; }
// swap all things that need to be swapped void swapTriFloat3Union(triFloat3Union* tf3u) { for(int i = 0; i < 3; i++) { swapBytes(tf3u->pts[i].x_.byte); swapBytes(tf3u->pts[i].y_.byte); swapBytes(tf3u->pts[i].z_.byte); } swapBytes(tf3u->normal.x_.byte); swapBytes(tf3u->normal.y_.byte); swapBytes(tf3u->normal.z_.byte); }
void reverseByteOrder(void *buffer, int width, int count) { RCF_ASSERT(width > 0)(width); RCF_ASSERT(count > 0)(count); if (width == 1) return; BOOST_STATIC_ASSERT( sizeof(char) == 1 ); char *chBuffer = static_cast<char *>(buffer); for (int i=0; i<count; i++) { for (int j=0;j<width/2;j++) { swapBytes( chBuffer + i*width + j, chBuffer + i*width + width - j - 1 ); } } }
// Routine to write a page from NAND Int32 nandHwDriverWritePage (Uint32 block, Uint32 page, Uint8 *data, nandProgramInfo_t *winfo) { Uint32 addr; if (data == NULL) return (-1); if ( (block >= hwDevInfo->totalBlocks) || (page >= hwDevInfo->pagesPerBlock) ) return (NAND_INVALID_ADDR); // Set Data Bus direction as OUT hwGpioSetDataBusDirection(GPIO_OUT); ndelay(TARGET_NAND_STD_DELAY); hwGpioClearOutput(NAND_NCE_GPIO_PIN); ndelay(TARGET_NAND_STD_DELAY*7); ptNandCmdSet(winfo->pageWriteCommandPre); ndelay(TARGET_NAND_STD_DELAY); // Send address of the block + page to be read // Address cycles = 4, Block shift = 22, Page Shift = 16, Bigblock = 0 addr = (block << hwDevInfo->blockOffset) + (page << hwDevInfo->pageOffset); if (hwDevInfo->lsbFirst == FALSE) addr = swapBytes (addr); ptNandAleSet(addr & 0xFF); // BIT0-7 1rst Cycle ndelay(TARGET_NAND_STD_DELAY); if (hwDevInfo->addressBytes >= 2) { ptNandAleSet((addr >> 8u) & 0x0F); // Bits8-11 2nd Cycle ndelay(TARGET_NAND_STD_DELAY); }
struct hacTree *hacTreeFromItems(const struct slList *itemList, struct lm *localMem, hacDistanceFunction *distF, hacMergeFunction *mergeF, hacCmpFunction *cmpF, void *extraData) /* Using distF, mergeF, optionally cmpF and binary tree operations, * perform a hierarchical agglomerative (bottom-up) clustering of * items. To free the resulting tree, lmCleanup(&localMem). */ // // Implementation: // // Create a pool containing all pairs of items (N*(N-1)/2), and build // a hierarchical binary tree of items from the bottom up. In each // iteration, first we find the closest pair and swap it into the head // of the pool; then we advance the head pointer, so the closest pair // now has a stable location in memory. Next, for all pairs still in // the pool, we replace references to the elements of the closest pair // with the closest pair itself, but delete half of such pairs because // they would be duplicates. Specifically, we keep pairs that had the // left element of the closest pair, and delete pairs that had the // right element of the closest pair. We rescore the pairs that have // the closest pair swapped in for an element. The code to do all // this is surprisingly simple -- in the second for loop below. Note // that with each iteration, the pool will reduce in size, by N-2 the // first iteration, N-3 the second, and so forth. // // An example may help: say we start with items A, B, C and D. Initially // the pool contains all pairs: // (A, B) (A, C) (A, D) (B, C) (B, D) (C, D) // // If (A, B) is the closest pair, we pop it from the pool and the pool // becomes // (A, C) (A, D) (B, C) (B, D) (C, D) // // Now we substitute (A, B) for pool pairs containing A, and delete pool // pairs contining B because they would be duplicates of those containing // A. [X] shows where a pair was deleted: // // ((A, B), C) ((A, B), D) [X] [X] (C, D) // // Now say ((A, B), D) is the closest remaining pair, and is popped from // the head of the pool. We substitute into pairs containing (A, B) and // delete pairs containing D. After the replacement step, the pool is // down to a single element: // // (((A, B), D), C) [X] { if (itemList == NULL) return NULL; struct hacTree *root = NULL; int itemCount = slCount(itemList); int pairCount = 0; struct hacTree *leafPairs = pairUpItems(itemList, itemCount, &pairCount, localMem, distF, mergeF, cmpF, extraData); int *nodesToDelete = needMem(pairCount * sizeof(int)); struct hacTree *poolHead = leafPairs; int poolLength = pairCount; while (poolLength > 0) { // Scan pool for node with lowest childDistance; swap that node w/head int bestIx = 0; double minScore = poolHead[0].childDistance; int i; for (i=1; i < poolLength; i++) if (poolHead[i].childDistance < minScore) { minScore = poolHead[i].childDistance; bestIx = i; } if (bestIx != 0) swapBytes((char *)&(poolHead[0]), (char *)&(poolHead[bestIx]), sizeof(struct hacTree)); // Pop the best (lowest-distance) node from poolHead, make it root (for now). root = poolHead; poolHead = &(poolHead[1]); poolLength--; // Where root->left is found in the pool, replace it with root. // Where root->right is found, drop that node so it doesn't become // a duplicate of the replacement cases. int numNodesToDelete = 0; for (i=0; i < poolLength; i++) { struct hacTree *node = &(poolHead[i]); if (node->left == root->left) // found root->left; replace node->left with root (merge root with node->right): initNode(node, root, node->right, distF, mergeF, extraData); else if (node->right == root->left) // found root->left; replace node->right with root (merge root with node->left): initNode(node, node->left, root, distF, mergeF, extraData); else if (node->left == root->right || node->right == root->right) // found root->right; mark this node for deletion: nodesToDelete[numNodesToDelete++] = i; } if (numNodesToDelete > 0) { int newPoolLen = nodesToDelete[0]; // This will be "next node to delete" for the last marked node: nodesToDelete[numNodesToDelete] = poolLength; for (i = 0; i < numNodesToDelete; i++) { int nodeToDel = nodesToDelete[i]; int nextNodeToDel = nodesToDelete[i+1]; int blkSize = nextNodeToDel - (nodeToDel+1); if (blkSize == 0) continue; struct hacTree *fromNode = &(poolHead[nodeToDel+1]); struct hacTree *toNode = &(poolHead[newPoolLen]); memmove(toNode, fromNode, blkSize * sizeof(struct hacTree)); newPoolLen += blkSize; } poolLength = newPoolLen; } // root now has a stable address, unlike nodes still in the pool, so set parents here: if (root->left != NULL) root->left->parent = root; if (root->right != NULL) root->right->parent = root; } // This shouldn't be necessary as long as initNode leaves parent pointers alone, // but just in case that changes: root->parent = NULL; return root; }
ulong MidiFile::getNext(FILE *f) { ulong x; fread(&x, 4, 1, f); return swapBytes(x); }
static void flipBytesFor32Bits(char* p) { swapBytes(p, p + 3); swapBytes(p + 1, p + 2); }
static void flipBytesFor16Bits(char* p) { swapBytes(p, p + 1); }
// Parse the XSVF, reversing the byte-ordering of all the bytestreams. // static FLStatus xsvfSwapBytes(XC *xc, struct Buffer *outBuf, uint32 *maxBufSize, const char **error) { FLStatus fStatus, retVal = FL_SUCCESS; uint32 newXSize = 0, curXSize = 0, totOffset = 0; uint32 numBytes; BufferStatus bStatus; uint8 thisByte; uint32 dummy; bool zeroMask = false; if ( !maxBufSize ) { maxBufSize = &dummy; } *maxBufSize = 0; thisByte = getNextByte(xc); while ( thisByte != XCOMPLETE ) { switch ( thisByte ) { case XTDOMASK:{ // Swap the XTDOMASK bytes. uint32 initLength; const uint8 *p; const uint8 *end; if ( newXSize != curXSize ) { curXSize = newXSize; sendXSize(outBuf, curXSize, error); } initLength = (uint32)outBuf->length; numBytes = bitsToBytes(curXSize); bStatus = bufAppendByte(outBuf, XTDOMASK, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, numBytes, outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); p = outBuf->data + initLength + 1; end = outBuf->data + outBuf->length; while ( *p == 0 && p < end ) p++; if ( p == end ) { // All zeros so delete the command outBuf->length = initLength; zeroMask = true; } else { // Keep the command if ( numBytes > *maxBufSize ) { *maxBufSize = numBytes; } zeroMask = false; } break; } case XSDRTDO: // Swap the tdiValue and tdoExpected bytes. if ( newXSize != curXSize ) { curXSize = newXSize; sendXSize(outBuf, curXSize, error); } numBytes = bitsToBytes(curXSize); if ( zeroMask ) { // The last mask was all zeros, so replace this XSDRTDO with an XSDR and throw away // the tdoExpected bytes. bStatus = bufAppendByte(outBuf, XSDR, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, numBytes, outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); while ( numBytes-- ) { getNextByte(xc); } } else { // The last mask was not all zeros, so we must honour the XSDRTDO's tdoExpected bytes. CHECK_STATUS( numBytes > BUF_SIZE, FL_UNSUPPORTED_SIZE_ERR, cleanup, "xsvfSwapBytes(): Previous mask was nonzero, but no room to compare %d bytes", numBytes); if ( numBytes > *maxBufSize ) { *maxBufSize = numBytes; } bStatus = bufAppendByte(outBuf, XSDRTDO, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapAndInterleaveBytes(xc, numBytes, outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); } break; case XREPEAT: // Drop XREPEAT for now. Will probably be needed for CPLDs. getNextByte(xc); break; case XRUNTEST: // Copy the XRUNTEST bytes as-is. bStatus = bufAppendByte(outBuf, XRUNTEST, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); bStatus = bufAppendByte(outBuf, getNextByte(xc), error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); bStatus = bufAppendByte(outBuf, getNextByte(xc), error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); bStatus = bufAppendByte(outBuf, getNextByte(xc), error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); bStatus = bufAppendByte(outBuf, getNextByte(xc), error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); break; case XSIR: // Swap the XSIR bytes. bStatus = bufAppendByte(outBuf, XSIR, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); thisByte = getNextByte(xc); bStatus = bufAppendByte(outBuf, thisByte, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, (uint32)bitsToBytes(thisByte), outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); break; case XSDRSIZE: // Just store it; if it differs from the old one it will be sent when required newXSize = getNextByte(xc); // Get MSB newXSize <<= 8; newXSize |= getNextByte(xc); newXSize <<= 8; newXSize |= getNextByte(xc); newXSize <<= 8; newXSize |= getNextByte(xc); // Get LSB break; case XSDR: // Copy over if ( newXSize != curXSize ) { curXSize = newXSize; sendXSize(outBuf, curXSize, error); } bStatus = bufAppendByte(outBuf, XSDR, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, bitsToBytes(curXSize), outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); break; case XSDRB: // Roll XSDRB, XSDRC*, XSDRE into one XSDR curXSize = newXSize; sendXSize(outBuf, curXSize, error); totOffset = (uint32)outBuf->length - 4; // each subsequent XSDRC & XSDRE updates this XSDRSIZE bStatus = bufAppendByte(outBuf, XSDR, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, bitsToBytes(newXSize), outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); break; case XSDRC: // Just add the XSDRC data to the end of the previous XSDR curXSize += newXSize; bStatus = bufWriteLongBE(outBuf, totOffset, curXSize, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, bitsToBytes(newXSize), outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); break; case XSDRE: // Just add the XSDRE data to the end of the previous XSDR curXSize += newXSize; bStatus = bufWriteLongBE(outBuf, totOffset, curXSize, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); fStatus = swapBytes(xc, bitsToBytes(newXSize), outBuf, error); CHECK_STATUS(fStatus, fStatus, cleanup, "xsvfSwapBytes()"); break; case XSTATE: // There doesn't seem to be much point in these commands, since the other commands have // implied state transitions anyway. Just make sure the TAP is initialised to be at // Run-Test/Idle before playing the CSVF stream. getNextByte(xc); break; case XENDIR: // Only the default XENDIR state (TAPSTATE_RUN_TEST_IDLE) is supported. Fail fast if // there's an attempt to switch the XENDIR state to PAUSE_IR. thisByte = getNextByte(xc); CHECK_STATUS( thisByte, FL_UNSUPPORTED_DATA_ERR, cleanup, "xsvfSwapBytes(): Only XENDIR(TAPSTATE_RUN_TEST_IDLE) is supported!"); break; case XENDDR: // Only the default XENDDR state (TAPSTATE_RUN_TEST_IDLE) is supported. Fail fast if // there's an attempt to switch the XENDDR state to PAUSE_DR. thisByte = getNextByte(xc); CHECK_STATUS( thisByte, FL_UNSUPPORTED_DATA_ERR, cleanup, "xsvfSwapBytes(): Only XENDDR(TAPSTATE_RUN_TEST_IDLE) is supported!"); break; default: // All other commands are unsupported, so fail if they're encountered. CHECK_STATUS( true, FL_UNSUPPORTED_CMD_ERR, cleanup, "xsvfSwapBytes(): Unsupported command 0x%02X!", thisByte); } thisByte = getNextByte(xc); } // Add the XCOMPLETE command bStatus = bufAppendByte(outBuf, XCOMPLETE, error); CHECK_STATUS(bStatus, FL_ALLOC_ERR, cleanup, "xsvfSwapBytes()"); cleanup: return retVal; }
// Last parameter exists to keep everything hidden in options template <class IArchive, class OArchive> inline void test_endian_serialization( typename IArchive::Options const & iOptions, typename OArchive::Options const & oOptions, const std::uint8_t inputLittleEndian ) { std::random_device rd; std::mt19937 gen(rd()); for(size_t i=0; i<100; ++i) { bool o_bool = random_value<uint8_t>(gen) % 2 ? true : false; uint8_t o_uint8 = random_value<uint8_t>(gen); int8_t o_int8 = random_value<int8_t>(gen); uint16_t o_uint16 = random_value<uint16_t>(gen); int16_t o_int16 = random_value<int16_t>(gen); uint32_t o_uint32 = random_value<uint32_t>(gen); int32_t o_int32 = random_value<int32_t>(gen); uint64_t o_uint64 = random_value<uint64_t>(gen); int64_t o_int64 = random_value<int64_t>(gen); float o_float = random_value<float>(gen); double o_double = random_value<double>(gen); std::vector<int32_t> o_vector(100); for(auto & elem : o_vector) elem = random_value<uint32_t>(gen); std::ostringstream os; { OArchive oar(os, oOptions); oar(o_bool); oar(o_uint8); oar(o_int8); oar(o_uint16); oar(o_int16); oar(o_uint32); oar(o_int32); oar(o_uint64); oar(o_int64); oar(o_float); oar(o_double); // We can't test vector directly here since we are artificially interfering with the endianness, // which can result in the size being incorrect oar(cereal::binary_data( o_vector.data(), static_cast<std::size_t>( o_vector.size() * sizeof(int32_t) ) )); } bool i_bool = false; uint8_t i_uint8 = 0; int8_t i_int8 = 0; uint16_t i_uint16 = 0; int16_t i_int16 = 0; uint32_t i_uint32 = 0; int32_t i_int32 = 0; uint64_t i_uint64 = 0; int64_t i_int64 = 0; float i_float = 0; double i_double = 0; std::vector<int32_t> i_vector(100); std::istringstream is(os.str()); { IArchive iar(is, iOptions); iar(i_bool); iar(i_uint8); iar(i_int8); iar(i_uint16); iar(i_int16); iar(i_uint32); iar(i_int32); iar(i_uint64); iar(i_int64); iar(i_float); iar(i_double); iar(cereal::binary_data( i_vector.data(), static_cast<std::size_t>( i_vector.size() * sizeof(int32_t) ) )); } // Convert to big endian if we expect to read big and didn't start big if( cereal::portable_binary_detail::is_little_endian() ^ inputLittleEndian ) // Convert to little endian if { CEREAL_TEST_SWAP_OUTPUT for( auto & val : o_vector ) swapBytes(val); } CEREAL_TEST_CHECK_EQUAL check_collection(i_vector, o_vector); }
ushort MidiFile::getNextShort(FILE *f) { ushort x; fread(&x, 2, 1, f); return swapBytes(x); }
int utTypesConversion(){ assert(base10To36( 0) == '0'); assert(base10To36( 9) == '9'); assert(base10To36(10) == 'a'); assert(base10To36(35) == 'z'); assert(base36To10('0') == 0); assert(base36To10('9') == 9); assert(base36To10('a') == 10); assert(base36To10('z') == 35); assert(bitsToUInt("00") == 0); assert(bitsToUInt("01") == 1); assert(bitsToUInt("10") == 2); assert(bitsToUInt("11") == 3); { //char big[] = { 64, 73, 15, -37 }; //float bigf = *(float *)big; //swapBytes(bigf); //assert(al::aeq( bigf, (float)M_PI )); uint16_t v2 = 0x0123; swapBytes(v2); assert(v2 == 0x2301); uint32_t v4 = 0x01234567; swapBytes(v4); assert(v4 == 0x67452301); uint64_t v8 = 0x0123456789abcdefULL; swapBytes(v8); assert(v8 == 0xefcdab8967452301ULL); union{ int32_t i; float f; } u; u.i = 0x01234567; swapBytes(u.f); assert(u.i == 0x67452301); } assert(toString(1) == "1"); assert(toString(1.1) == "1.1"); assert(toString(-1.1) == "-1.1"); // Signed 16-bit integer and unit real conversions for(int i=-32768; i<32768; ++i){ float f = float(i)/32768; assert(unitToInt16(f) == i); assert(intToUnit(int16_t(i)) == f); } assert(uintToUnit<float>(1<< 0) == 0.00); assert(uintToUnit<float>(1UL<<29) == 1./8); assert(uintToUnit<float>(1UL<<30) == 1./4); assert(uintToUnit<float>(1UL<<31) == 1./2); assert(uintToUnitS<float>(1UL<<31) == 0.0); assert(uintToUnitS<float>((1UL<<31) - (1<<30)) ==-0.5); assert(uintToUnitS<float>((1UL<<31) + (1<<30)) ==+0.5); //assert(unitToUInt2(0.0) == 0); //printf("%lu %lu\n", unitToUInt2(1./8), 1UL<<29); assert(unitToUInt2(1./8) == (1UL<<29)); assert(unitToUInt2(1./4) == (1UL<<30)); assert(unitToUInt2(1./2) == (1UL<<31)); assert(unitToUInt8(0) == 0); assert(unitToUInt8(1./8) == 32); assert(unitToUInt8(1./4) == 64); assert(unitToUInt8(1./2) == 128); return 0; }
void writeGap(struct gapInfo *gap, struct xaAli *xa, int symStart, int symEnd, char geneStrand, FILE *f) /* Write out info on one gap to file. */ { char qStart[totSize+1], qEnd[totSize+1]; char tStart[totSize+1], tEnd[totSize+1]; char hStart[totSize+1], hEnd[totSize+1]; int s, e, size; int midSize; int i; char *threePrime, *fivePrime; boolean isQgap; fprintf(f, "%s %s %s hom %s:%d-%d %c %s:%d-%d %c slide %d\n", gapTypeStrings[gap->type], (gap->hasIntronEnds ? " intron" : "!intron"), (gap->hasStrongHomology ? "heavy" : "light"), gap->query, gap->qStart, gap->qEnd, xa->qStrand, gap->target, gap->tStart, gap->tEnd, geneStrand, gap->slideCount); s = symStart-exSize; e = symStart + inSize; if (s < 0) s = 0; size = e-s; uglyf("s %d size %d e %d totSize %d\n", s, size, e, totSize); strncpy(qStart, xa->qSym+s, size); strncpy(tStart, xa->tSym+s, size); strncpy(hStart, xa->hSym+s, size); qStart[size] = tStart[size] = hStart[size] = 0; // uglyf - crashes by here s = symEnd-inSize; midSize = s - e; e = symEnd+exSize; if (e > xa->symCount) e = xa->symCount; size = e-s; strncpy(qEnd, xa->qSym+s, size); strncpy(tEnd, xa->tSym+s, size); strncpy(hEnd, xa->hSym+s, size); qEnd[size] = tEnd[size] = hEnd[size] = 0; if (gap->isRc) { swapBytes(qStart, qEnd, totSize); swapBytes(tStart, tEnd, totSize); swapBytes(hStart, hEnd, totSize); reverseComplement(qStart, totSize); reverseComplement(qEnd, totSize); reverseComplement(tStart, totSize); reverseComplement(tEnd, totSize); reverseBytes(hStart, totSize); reverseBytes(hEnd, totSize); } /* Write out ends of gap to file. */ fprintf(f, "%s ...%d... %s\n", qStart, midSize, qEnd); fprintf(f, "%s ...%d... %s\n", tStart, midSize, tEnd); fprintf(f, "%s ...%d... %s\n\n", hStart, midSize, hEnd); /* Add intron ends to consensus sequence histogram. */ if (gap->hasIntronEnds && gap->type == cCodingGap) { isQgap = (qStart[exSize] == '-'); if (isQgap) { fivePrime = tStart; threePrime = tEnd; } else { fivePrime = qStart; threePrime = qEnd; } if (noInserts(threePrime, totSize) && noInserts(fivePrime, totSize) ) { int *homoCount; for (i=0; i<totSize; ++i) { hist5[i][histIx(fivePrime[i])] += 1; hist3[i][histIx(threePrime[i])] += 1; } ++histCount; if (isQgap) { ++ceOnlyCount; homoCount = ceOnlyHomoCount; } else { ++cbOnlyCount; homoCount = cbOnlyHomoCount; } ++bothCount; for (i=0; i<totSize; ++i) { if (fivePrime[i] == threePrime[i]) { homoCount[i] += 1; bothHomoCount[i] += 1; } } /* Add introns to list. */ { char idBuf[2*intronEndsSize+1]; struct intronList *il; struct hashEl *hel; memcpy(idBuf, fivePrime+exSize, intronEndsSize); memcpy(idBuf+intronEndsSize, threePrime, intronEndsSize); idBuf[ sizeof(idBuf)-1 ] = 0; if ((hel = hashLookup(intronHash, idBuf)) != NULL) { il = hel->val; il->count += 1; fprintf(f, ">>>%d of set<<<\n", il->count); if (il->isQgap != isQgap) { il->onBoth = TRUE; } } else { AllocVar(il); strcpy(il->ends, idBuf); il->count = 1; il->isQgap = isQgap; slAddHead(&intronList, il); hashAdd(intronHash, idBuf, il); } } } else { static insertCount = 0; warn("Skipping intron with flanking inserts %d", ++insertCount); } } }