Important Snippets


dvmatrix2
tga
bleh
resizeimage
tiny jpeg loader
stripextension
swaprgb
deg2rad
framebuffer
sepstr
strintolower
ADC mega32
test
mergealpha
fileexists
dec2bin
debugprint
dvmatrix
wait
geilomat
shuffle
isinstring
dv10-3

dvmatrix2
/*    3x3 Matrix einlesen
    Philipp Karbach
    13.05.08*/


#include <stdio.h>

#define N 10


int main()
{
  float vek[N],Rvek[N];
  float matrix[N+1][N];
  int n=0,z=0,s=0,dim=0;

  printf("Dimension eingeben [1-10]: ");
  scanf("%d",&dim);

  if(dim<=0||dim>10) {
    printf("Ungültige Dimension! Ende.\n");
    return 0;
  }

  printf("R%d Vektor eingeben:\n",dim);
  
  for(z=0;z<dim;z++) {
    printf("x%d: ",z);    
    scanf("%f",&vek[z]);
  }

  printf("Eingegebener Vektor:\n");

  for(z=0;z<dim;z++)
    printf("x%d: %4f\n",z,vek[z]);



  printf("Matrix eingeben:\n");

  for(n=0;n<dim;n++) {
    printf("Matrix Zeile %d eingeben: \n",n+1);
    for(z=0;z<dim;z++) {
        printf("Z%dX%d: ",n,z);
        scanf("%f",&matrix[z][n]);
    }        
  }

  printf("Eingegebene Matrix:\n");

  for(n=0;n<dim;n++) {
    for(z=0;z<dim;z++) {
        printf(" %4.2f ",matrix[z][n]);
    }
    printf("\n");        
  }

  // Matrix * Vektor
  // Skalarprodukt: Zeilenvektor(Matrix)*Spaltenvektor(Vektor)

  for(n=0;n<dim;n++) {
    s=0;
    for(z=0;z<dim;z++) {
        Rvek[n] += vek[s]*matrix[z][n];
        s++;        
    }            
  }

  printf("Ergebnis Matrix*Vektor:\n");


  for(z=0;z<dim;z++)
    printf("x%d: %f\n",z,Rvek[z]);
  
  


  return 0;
}

top

tga
typedef unsigned char     byte;


typedef struct Image_t
{            
    int width;                
    int height;
    int bpp;
    unsigned char *data;
    char name[16];
} Image;



void WriteTGA(char *file, Image *tempImage);
Image* LoadTGA(char *filename);

void WriteTGA(char *file, Image *tempImage)
{

   FILE *File;              
   unsigned char uselessChar; 
   short int uselessInt;     
   unsigned char imageType;  
   int index;                
   unsigned char bits;  
   long Size;                 
   int colorMode;
   unsigned char tempColors;
   int cnt=0;

   int width  = tempImage->width;
   int height = tempImage->height;


   File = fopen(file, "wb");

 
   if(!File) { fclose(File); return ; }
 
   imageType = 2; colorMode = 3; bits = 24;
   uselessChar = 0; uselessInt = 0;

  
   fwrite(&uselessChar, sizeof(unsigned char), 1, File);
   fwrite(&uselessChar, sizeof(unsigned char), 1, File);


   fwrite(&imageType, sizeof(unsigned char), 1, File);


   fwrite(&uselessInt, sizeof(short int), 1, File);
   fwrite(&uselessInt, sizeof(short int), 1, File);
   fwrite(&uselessChar, sizeof(unsigned char), 1, File);
   fwrite(&uselessInt, sizeof(short int), 1, File);
   fwrite(&uselessInt, sizeof(short int), 1, File);


   fwrite(&width, sizeof(short int), 1, File);
   fwrite(&height, sizeof(short int), 1, File);
   fwrite(&bits, sizeof(unsigned char), 1, File);

   fwrite(&uselessChar, sizeof(unsigned char), 1, File);


   Size = width * height * colorMode;

   

   for(index = 0; index < Size; index += colorMode)
   {
       int mod=0;
       tempColors = tempImage->data[index];
       tempImage->data[index] = tempImage->data[index + 2];
       tempImage->data[index + 2] = tempColors;
       
       cnt = (index*100)/Size;

       mod = cnt%10;
   }


   printf("writing tga.\n");
   fwrite(tempImage->data, sizeof(unsigned char), Size, File);
   fclose(File);
   printf("done.\n");
}

void StripExtension( const char *in, char *out ) {
    while ( *in && *in != '.' ) {
        *out++ = *in++;
    }
    *out = 0;
}

Image* LoadTGA(char *filename)
{
    byte    TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};
    byte    TGAcompare[12];
    byte    header[6];                             
    int     imageSize;
    Image    *tempImage=NULL;
    FILE    *File;
    int        t, i;

    tempImage = (Image*)malloc(sizeof(Image));
                                                    
    File = fopen(filename, "rb");
    if (fread(TGAcompare,1,sizeof(TGAcompare),File)!=sizeof(TGAcompare))   return NULL;
    if (memcmp(TGAheader,TGAcompare,sizeof(TGAheader))!=0)                 return NULL;
    if (fread(header,1,sizeof(header),File)!=sizeof(header))               return NULL;

    tempImage->width  = header[1] * 256 + header[0];
    tempImage->height = header[3] * 256 + header[2];
    tempImage->bpp = header[4];
    imageSize = tempImage->width*tempImage->height*tempImage->bpp/8;
    sprintf(tempImage->name,filename);
    StripExtension(tempImage->name,tempImage->name);


    tempImage->data = (byte *) malloc ( imageSize );
    if (fread(tempImage->data, 1, imageSize, File) != (unsigned int)imageSize)
    {
        free (tempImage->data);
    }
    
    
    for (i = 0;i<imageSize;i+= tempImage->bpp/8)
    {
        t = tempImage->data[i];
        tempImage->data[i] = tempImage->data[i+2];
        tempImage->data[i+2] = t;
    }

    fclose (File);
    return tempImage;
}

bleh
boyd 1# hinv -v
1 400 MHZ IP30 Processor
Heart ASIC: Revision F
CPU: MIPS R12000 Processor Chip Revision: 3.5
FPU: MIPS R12010 Floating Point Chip Revision: 0.0
Main memory size: 1536 Mbytes
Xbow ASIC: Revision 1.3
Instruction cache size: 32 Kbytes
Data cache size: 32 Kbytes
Secondary unified instruction/data cache size: 2 Mbytes
Integral SCSI controller 0: Version QL1040B (rev. 2), single ended
  Disk drive: unit 1 on SCSI controller 0 (unit 1)
Integral SCSI controller 1: Version QL1040B (rev. 2), single ended
IOC3/IOC4 serial port: tty1
IOC3/IOC4 serial port: tty2
IOC3 parallel port: plp1
Graphics board: V6
Integral Fast Ethernet: ef0, version 1, pci 2
Iris Audio Processor: version RAD revision 12.0, number 1
  PCI Adapter ID (vendor 0x10a9, device 0x0003) PCI slot 2
  PCI Adapter ID (vendor 0x1077, device 0x1020) PCI slot 0
  PCI Adapter ID (vendor 0x1077, device 0x1020) PCI slot 1
  PCI Adapter ID (vendor 0x10a9, device 0x0005) PCI slot 3
boyd 2# 


resizeimage
XFactor = (double)image->width/(double)tempImage->width;
YFactor = (double)image->height/(double)tempImage->height;


for(x=0;x<tempImage->width;x++) {
    for(y=0;y<tempImage->height;y++) {
        int curPixel = (int)floor(y*YFactor)*3 + ((image->width*(int)floor(x*XFactor))*3);
 
        tempImage->data[y*3 + (tempImage->width*x*3)]   =
            image->data[curPixel];
 
        tempImage->data[y*3 + (tempImage->width*x*3)+1] =
            image->data[curPixel+1];
 
        tempImage->data[y*3 + (tempImage->width*x*3)+2] =
            image->data[curPixel+2];
    }
}

tiny jpeg loader
//#include \"tjpgd.h\"
char Work[3100];
typedef struct {
    FILE *fp;
    BYTE *data;
    int width;
    int height;
} JPEGimage;

UINT in_func (JDEC* jd, BYTE* buff, UINT nbyte) {
    JPEGimage *dev = (JPEGimage*)jd->device;
    if (buff) {
        return (UINT)fread(buff, 1, nbyte, dev->fp);
    } else {
        return fseek(dev->fp, nbyte, SEEK_CUR) ? 0 : nbyte;
    }
}
void drawjpeg(int x,int y,JPEGimage *img)
{
    int i=0,j=0;

    for(i=0;i<img->width;i++) {
        for(j=0;j<img->height;j++) {
            int r = img->data[(3*i + j*(img->width)*3)];    
            int g = img->data[(3*i + j*(img->width)*3)+1];
            int b = img->data[(3*i + j*(img->width)*3)+2];

            setpixel(x+i,y+j,r,g,b);
        }
    }
}
UINT out_func (JDEC* jd, void* bitmap, JRECT* rect)
{
    JPEGimage *dev = (JPEGimage*)jd->device;
    BYTE *src = (BYTE*)bitmap;
    BYTE *dst;
    UINT y, bws, bwd;
    dst = dev->data + 3 * (rect->top * dev->width + rect->left);
    bws = 3 * (rect->right - rect->left + 1);
    bwd = 3 * dev->width;
    for (y = rect->top; y <= rect->bottom; y++) {
        memcpy(dst, src, bws);
        src += bws; dst += bwd;
    }
    return 1; 
}
/*
JPEGimage *img=0;
img = load_jpg(\"test.jpg\", Work, 3100);
drawjpeg(100,100,img);
*/
JPEGimage *load_jpg (const char* fn,void *work,UINT sz_work) {
    JDEC jd;
    JRESULT rc;
    
    JPEGimage *image = (JPEGimage*)malloc(sizeof(JPEGimage));
    image->fp = fopen(fn, \"rb\");
    rc = jd_prepare(&jd, in_func, work, sz_work, image);

    if (rc == JDR_OK) {
        image->data = malloc(3 * jd.width * jd.height);
        image->width = jd.width;
        image->height = jd.height;
        rc = jd_decomp(&jd, out_func, 0);        
    } else {
        printf(\"Error: %d\\n\", rc);
    }
    return image;
}

stripextension
void StripExtension( const char *in, char *out ) {
    while ( *in && *in != '.' ) {
        *out++ = *in++;
    }
    *out = 0;
}

swaprgb
void SwapRGB(void* buffer)                                        
{
    void* b = buffer;                                            
    __asm                                                        
    {
        mov ecx, 512*512                                    
        mov ebx, b                                                
        label:                                                    
            mov al,[ebx+0]                                        
            mov ah,[ebx+2]                                        
            mov [ebx+2],al                                        
            mov [ebx+0],ah                                    
            
            add ebx,3                                            
            dec ecx                                                
            jnz label                                        
    }
}

deg2rad
float deg2rad(float deg)
{
    return (float)(deg * (M_PI / 180.0));
}

float rad2deg(float rad)
{
    return (float)(rad * (180.0 / M_PI));
}

framebuffer
#include <iostream>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <linux/types.h>
#include <linux/fb.h>
#include <math.h>

class TError {
public:
    TError(const char *msg) {
        this->msg = msg;
    }
    TError(const TError bitand e) {
        msg = e.msg;
    }
    void Output() {
        std::cerr << msg << std::endl;
    }
    virtual ~TError() {}
protected:
    TError bitand operator=(const TError bitand);
private:
    const char *msg;
};

// Linear memory based image
class TRect {
public:
    TRect():  Addr(0), Size(0), Width(0), Height(0), LineLen(0), BPP(16) {
    }
    virtual ~TRect() {
    }
    bool DrawRect(const TRect bitand SrcRect, int x, int y) const {
        if (BPP not_eq 16 or SrcRect.BPP not_eq 16) {
            // don't support that yet
            throw TError("does not support other than 16 BPP yet");
        }

        // clip
        int x0, y0, x1, y1;
        x0 = x;
        y0 = y;
        x1 = x0 + SrcRect.Width - 1;
        y1 = y0 + SrcRect.Height - 1;
        if (x0 < 0) {
            x0 = 0;
        }
        if (x0 > Width - 1) {
            return true;
        }
        if( x1 < 0) {
            return true;
        }
        if (x1 > Width - 1) {
            x1 = Width - 1;
        }
        if (y0 < 0) {
            y0 = 0;
        }
        if (y0 > Height - 1) {
            return true;
        }
        if (y1 < 0) {
            return true;
        }
        if (y1 > Height - 1) {
            y1 = Height -1;
        }

        //copy
        int copyLineLen = (x1 + 1 - x0) * BPP / 8;
        unsigned char *DstPtr = Addr + LineLen * y0 + x0 * BPP / 8;
        const unsigned char *SrcPtr = SrcRect.Addr + SrcRect.LineLen *(y0 - y) + (x0 - x) * SrcRect.BPP / 8;

        for (int i = y0; i <= y1; i++) {
            memcpy(DstPtr, SrcPtr, copyLineLen);
            DstPtr += LineLen;
            SrcPtr += SrcRect.LineLen;
        }
        
        
        return true;
    }

    bool DrawRect(const TRect bitand rect) const { // default is Center
        return DrawRect(rect, (Width - rect.Width) / 2, (Height - rect.Height) / 2);
    }

    bool Clear() const {
        int i;
        unsigned char *ptr;
        for (i = 0, ptr = Addr; i < Height; i++, ptr += LineLen) {
            memset(ptr, 0, Width * BPP / 8);
        }
        return true;
    }

protected:
    TRect(const TRect bitand);
    TRect bitand operator=( const TRect bitand);

protected:
    unsigned char *Addr;
    int Size;
    int Width, Height, LineLen;
    unsigned BPP;
};



class TFrameBuffer: public TRect {
public:
    TFrameBuffer(const char *DeviceName = "/dev/fb0"): TRect(), fd(-1) {
        Addr = (unsigned char *)MAP_FAILED;

            fd = open(DeviceName, O_RDWR);
        if (fd < 0) {
            throw TError("cannot open frame buffer");
        }

            struct fb_fix_screeninfo Fix;
            struct fb_var_screeninfo Var;
        if (ioctl(fd, FBIOGET_FSCREENINFO, bitand Fix) < 0 or ioctl(fd, FBIOGET_VSCREENINFO, bitand Var) < 0) {
            throw TError("cannot get frame buffer information");
        }

        BPP = Var.bits_per_pixel;
            if (BPP not_eq 16) {
            throw TError("support 16BPP frame buffer only");
        }

            Width  = Var.xres;
            Height = Var.yres;
            LineLen = Fix.line_length;
              Size = LineLen * Height;

        int PageSize = getpagesize();
        Size = (Size + PageSize - 1) / PageSize * PageSize ;
            Addr = (unsigned char *)mmap(NULL, Size, PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0);
        if (Addr == (unsigned char *)MAP_FAILED) {
            throw TError("map frame buffer failed");
            return;
        }
        ::close(fd);
        fd = -1;

        Clear();
    }

    virtual ~TFrameBuffer() {
        ::munmap(Addr, Size);
        Addr = (unsigned char *)MAP_FAILED;

        ::close(fd);
        fd = -1;
    }

protected:
    TFrameBuffer(const TFrameBuffer bitand);
    TFrameBuffer bitand operator=( const TFrameBuffer bitand);
private:
    int fd;
};

class TVideo : public TRect {
public:
    TVideo(const char *DeviceName = "/dev/camera"): TRect(), fd(-1) {
        Addr = 0;

        Width = 240;
        Height = 320;
        BPP = 16;
        LineLen = Width * BPP / 8;
        Size = LineLen * Height;
        Addr = new unsigned char<:Size:>;

        Clear();
    }

    bool FetchPicture(int x,int y) const {
         int location = (x) * (BPP/8) + (y) * LineLen;
        Addr[location] = 0xff; /* A little green */


        
        return true;
    }

    virtual ~TVideo() {
        delete<::> Addr;
        Addr = 0;
    }

protected:
    TVideo(const TVideo bitand);
    TVideo bitand operator=(const TVideo bitand);

private:
    int fd;
};

int main(int argc, char **argv)
{
    float t=0.0;
    int i=0;
    TFrameBuffer FrameBuffer;
    TVideo Video;

    for(i=0;i<20000;i++) {
        float Sine=sin(0.2*t)*60+180;
        Video.FetchPicture((int)t,(int)Sine);
        FrameBuffer.DrawRect(Video);
        t+=0.015;
    }
    return 0;
}

sepstr
static void SepStr(char *AB, char Sep, char *A, char *B)
{
    char *pc;
    char sAB[256];
 
    strcpy(sAB, AB);
    pc=strchr(sAB, Sep);
    if (pc==NULL)
    {
        if (A!=NULL) strcpy(A, sAB);
        if (B!=NULL) strcpy(B, "");
        return;
    }
    *pc=0;
    if (A!=NULL) strcpy(A, sAB);
    if (B!=NULL) strcpy(B, pc+1);
}
static void RSepStr(char *AB, char Sep, char *A, char *B)
{
    char *pc;
    char sAB[256];
 
    strcpy(sAB, AB);
    pc=strrchr(sAB, Sep);
    if (pc==NULL)
    {
        if (A!=NULL) strcpy(A, sAB);
        if (B!=NULL) strcpy(B, "");
        return;
    }
    *pc=0;
    if (A!=NULL) strcpy(A, sAB);
    if (B!=NULL) strcpy(B, pc+1);
}

strintolower
string tolower(const string &str)
{
   string result=str;
   for(int i=0;i<result.size();++i)
      result[i]=tolower(result[i]);
   return result;
}

ADC mega32
int ReadChannel(int channel)
{
  int i;
  int result = 0;
  ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);
  ADMUX = channel;
  ADMUX |= (1<<REFS1) | (1<<REFS0);
  ADCSRA |= (1<<ADSC);
  while (ADCSRA&(1<<ADSC));
  for(i=0;i<4;i++)
  {
    ADCSRA |= (1<<ADSC);
    while (ADCSRA&(1<<ADSC));
    result += ADCW;
  }
  ADCSRA &= ~(1<<ADEN); 
  result /= 4; 
  return result;
}

test
hello my name is ubersoldier

mergealpha
    for(int i=0;i<imageSize;i++) {
        tempImage->data[i] = ((Rock->data[i]*AlphaMap->data[i])/255) +
                             ((Dirt->data[i]*(255-AlphaMap->data[i]))/255);
    }


fileexists
bool FileExists(char *filename)
{
    FILE *exists;

    exists = fopen(filename,"rb");

    if(!exists) {
        return false;
    } else {        
        return true;
    }
    
    fclose(exists);
}

dec2bin
char buf[80];
int wert = 1234;
itoa(wert, buf, 10);  // Dezimal "1234"
itoa(wert, buf, 8);   // Oktal "2322"
itoa(wert, buf, 16);  // Hexadezimal "4d2"
itoa(wert, buf, 2);   // binär "10011010010"

debugprint
void print(char *string, ...)
{
    char        text[1024];
    va_list        va;

    if (string==NULL) return;

    va_start(va, string);
        vsprintf(text, string, va);
    va_end(va);

    MessageBox(NULL,text,"Engine Debug Message:",NULL);
}

dvmatrix
/*    3x3 Matrix einlesen
    Philipp Karbach
    13.05.08*/


#include <stdio.h>

#define N 3


int main()
{
  float vek[N],Rvek[N];
  float matrix[N+1][N];
  int n=0,z=0,s=0;

  printf("R3 Vektor eingeben [x,y,z]: ");
  scanf("%f %f %f",&vek[0],&vek[1],&vek[2]);

  printf("Vektor: x: %f y: %f z: %f\n",vek[0],vek[1],vek[2]);

  printf("Matrix eingeben:\n");

  for(n=0;n<N;n++) {
    printf("%d.Zeile eingeben [x%d,y%d,z%d]:",n+1,z,z+1,z+2);
    scanf("%f %f %f",&matrix[z][n],&matrix[z+1][n],&matrix[z+2][n]);
    z++;
  }

  z=0;

  for(n=0;n<N;n++) {
    printf("%f %f %f\n",matrix[z][n],matrix[z+1][n],matrix[z+2][n]);
    z++;
  }

  
  // Berechnen von matrix*vek
  // zeile(matrix)*spalte(vektor)
  z=0;

  for(n=0;n<N;n++) {
    s=0;
    Rvek[n] = matrix[z][n]*vek[s] + matrix[z+1][n]*vek[s+1] + matrix[z+2][n]*vek[s+2];
    z++;
  }


  printf("Ergebnis: x: %f y: %f z: %f\n",Rvek[0],Rvek[1],Rvek[2]);
  



  


  return 0;
}


wait
bool wait(float sleeptime) 
{
    if(!render) {
        if(starttime - Lasttime < sleeptime) return false;    
        Lasttime = starttime;
    } else {
        if(timeFromStart - Lasttime < sleeptime) return false;
        Lasttime = timeFromStart;
    }
    return true;
}

geilomat
/******************************************************************************
 *    fbtest - fbtest.c
 *    test program for the tuxbox-framebuffer device
 *    tests all GTX/eNX supported modes
 *                                                                            
 *    (c) 2003 Carsten Juttner (carjay@gmx.net)
 *
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     The Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program; if not, write to the Free Software
 *     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *                                            
 ******************************************************************************
 * $Id: fbtest.c,v 1.4 2003/12/22 02:54:23 carjay Exp $
 ******************************************************************************/

// TODO: - should restore the colour map and mode to what it was before
//     - is colour map handled correctly?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <fcntl.h>

#include <linux/fb.h>

#include <error.h>

#define FBDEV "/dev/fb/0"

struct vidsize{
    int width;
    int height;
};
static
const struct vidsize vidsizetable[]={    // all supported sizes
    {720,576},{720,480},{720,288},{720,240},
    {640,576},{640,480},{640,288},{640,240},
    {360,576},{360,480},{360,288},{360,240},
    {320,576},{320,480},{320,288},{320,240}
};
#define VIDSIZENUM (sizeof(vidsizetable)/sizeof(struct vidsize))

enum pixenum{    // keep in sync with pixname !
    CLUT4=0,
    CLUT8,
    RGB565,
    ARGB1555,
    ARGB
};
const char *pixname[] = {
    "CLUT4",
    "CLUT8",
    "RGB565",
    "ARGB1555",
    "ARGB"
};

struct pixelformat{
    char *name;
    struct fb_bitfield red;
    struct fb_bitfield green;
    struct fb_bitfield blue;
    struct fb_bitfield transp;
    char bpp;
    char pixenum;
};

static        // so far these are all modes supported by the eNX (only partially by GTX)
const struct pixelformat pixelformattable[] = {
    { .name = "CLUT4 ARGB8888",     // CLUT4 (ARGB8888)
        .bpp = 4, .pixenum = CLUT4,
        .red =      { .offset = 0, .length=8, .msb_right =0 },
        .green = { .offset = 0, .length=8, .msb_right =0 },
        .blue =  { .offset = 0, .length=8, .msb_right =0 },
        .transp=  { .offset = 0, .length=8, .msb_right =0 }
    },
    { .name = "CLUT4 ARGB1555",     // CLUT4 (ARGB1555)
        .bpp = 4, .pixenum = CLUT4,
        .red =      { .offset = 0, .length=5, .msb_right =0 },
        .green = { .offset = 0, .length=5, .msb_right =0 },
        .blue =  { .offset = 0, .length=5, .msb_right =0 },
        .transp=  { .offset = 0, .length=1, .msb_right =0 }
    },
    { .name = "CLUT8 ARGB8888",    // CLUT8 (ARGB8888)
        .bpp = 8, .pixenum = CLUT8,
        .red =      { .offset = 0, .length=8, .msb_right =0 },
        .green = { .offset = 0, .length=8, .msb_right =0 },
        .blue =  { .offset = 0, .length=8, .msb_right =0 },
        .transp=  { .offset = 0, .length=8, .msb_right =0 }
    },
    { .name = "CLUT8 ARGB1555",    // CLUT8 (ARGB1555)
        .bpp = 8, .pixenum = CLUT8,
        .red =      { .offset = 0, .length=5, .msb_right =0 },
        .green = { .offset = 0, .length=5, .msb_right =0 },
        .blue =  { .offset = 0, .length=5, .msb_right =0 },
        .transp=  { .offset = 0, .length=1, .msb_right =0 }
    },
    { .name = "ARGB1555",     // ARGB1555
        .bpp = 16, .pixenum = ARGB1555,
        .red =      { .offset = 10, .length=5, .msb_right =0 },
        .green = { .offset = 5,  .length=5, .msb_right =0 },
        .blue =  { .offset = 0,  .length=5, .msb_right =0 },
        .transp=  { .offset = 15, .length=1, .msb_right =0 }
    },
    { .name = "RGB565",         // RGB565
        .bpp = 16, .pixenum = RGB565,
        .red =      { .offset = 11, .length=5, .msb_right =0 },
        .green = { .offset = 5,  .length=6, .msb_right =0 },
        .blue =  { .offset = 0,  .length=5, .msb_right =0 },
        .transp=  { .offset = 0,  .length=0, .msb_right =0 }
    },
    { .name = "ARGB",    // 32 f*cking bits, the real McCoy :)
        .bpp = 32, .pixenum = ARGB,
        .red =      { .offset = 16, .length=8, .msb_right =0 },
        .green = { .offset = 8,  .length=8, .msb_right =0 },
        .blue =  { .offset = 0,  .length=8, .msb_right =0 },
        .transp=  { .offset = 24, .length=8, .msb_right =0 }
    }
};
#define PIXELFORMATNUM (sizeof(pixelformattable)/sizeof(struct pixelformat))

struct colour {
    __u16 r;
    __u16 g;
    __u16 b;
    __u16 a;
};
static
struct colour colourtable[] = {
    {.r =0xffff, .g = 0xffff, .b=0xffff, .a=0xffff},    // fully transparent white
    {.r =0xffff, .g = 0x0000, .b=0x0000, .a=0x0000},    // red
    {.r =0x0000, .g = 0xffff, .b=0x0000, .a=0x0000},    // green
    {.r =0x0000, .g = 0x0000, .b=0xffff, .a=0x0000},    // blue
    {.r =0x0000, .g = 0x0000, .b=0x0000, .a=0x0000}        // black
};
#define COLOURNUM (sizeof(colourtable)/sizeof(struct colour))

struct rect{
    int x;
    int y;
    int width;
    int height;
    const struct colour *col;
};
struct pixel{        // up to 32 bits of pixel information
    char byte[4];
};

void col2pixel (struct pixel *pix, const struct pixelformat *pixf, const struct colour *col){
    switch (pixf->pixenum){
        case RGB565:
            pix->byte[0]=(col->r&0xf8)|(col->g&0xfc)>>5;
            pix->byte[1]=(col->g&0xfc)<<3|(col->b&0xf8)>>3;
            break;
        case ARGB1555:
            pix->byte[0]=(col->a&0x80)|(col->r&0xf8)>>1|(col->g&0xf8)>>6;
            pix->byte[1]=(col->g&0xf8)<<2|(col->b&0xf8)>>3;
            break;
        case ARGB:
            pix->byte[0]=col->a;
            pix->byte[1]=col->r;
            pix->byte[2]=col->g;
            pix->byte[3]=col->b;
            break;
        default:
            printf ("unknown pixelformat\n");
            exit(1);
    }
}

int setmode(int fbd, const struct pixelformat *pixf,const struct vidsize *vids){
    struct fb_var_screeninfo var;
    int stat;
    stat = ioctl (fbd, FBIOGET_VSCREENINFO,&var);
    if (stat<0) return -2;
    
    var.xres= vids->width;
    var.xres_virtual = vids->width;
    var.yres= vids->height;
    var.yres_virtual = vids->height;
    
    var.bits_per_pixel = pixf->bpp;
    var.red = pixf->red;
    var.green = pixf->green;
    var.blue = pixf->blue;
    var.transp = pixf->transp;

    stat = ioctl (fbd, FBIOPUT_VSCREENINFO,&var);
    if (stat<0) return -1;
    return 0;
}

// unefficient implementation, do NOT use it for your next ego shooter, please :)
// for 4-Bit only rectangles with even width are supported
// CLUT-modes use value of red component as index
void drawrect(void *videoram, struct rect *r, const struct pixelformat *pixf, const struct vidsize *vids){
    int x,y,corwidth, bpp = 0, tocopy = 1;
    struct pixel pix;
    unsigned char *pmem = videoram;
    corwidth = r->width;    // actually only "corrected" for 4 Bit

    if (pixf->pixenum!=CLUT4&&pixf->pixenum!=CLUT8){
        switch (pixf->pixenum){
            case ARGB1555:
            case RGB565:
                bpp = 16;
                tocopy = 2;
                break;
            case ARGB:
                bpp = 32;
                tocopy = 4;
                break;
            default:
                printf ("drawrect: unknown pixelformat(%d) bpp:%d\n",pixf->pixenum,pixf->bpp);
                exit(1);
        }
        col2pixel(&pix,pixf,r->col);
    } else {
        switch (pixf->pixenum){    // CLUT = Colour LookUp Table (palette)
            case CLUT4:    // take red value as index in this case
                pix.byte[0]=(r->col->r)<<4|(r->col->r&0xf);    // slightly cryptic... "rect->colour->red"
                corwidth>>=1;    // we copy bytes
                bpp=4;
                tocopy=1;
                break;
            case CLUT8:
                pix.byte[0]=(r->col->r&0xff);
                bpp=8;
                tocopy=1;
                break;
        }
    }
    pmem=videoram+((((r->y*vids->width)+r->x)*bpp)>>3);
    for (y=0;y<r->height;y++){
        int offset = 0;
        for (x=0;x<corwidth;x++){
            memcpy (pmem+offset,pix.byte,tocopy);
            offset+=tocopy;
        }
        pmem +=((vids->width*bpp)>>3);    // skip one whole line, actually should be taken from "fix-info"
    }
}
            
// create quick little test image, 4 colours from table
void draw4field(void *videoram, const struct pixelformat *pixf, const struct vidsize *vids){
    struct rect r;
    struct colour c;
    int height, width;
    c.r = 1;    // only used for the indexed modes, r is taken as index
    height = vids->height;
    width = vids->width;

    r.height = height>>1;
    r.width = width>>1;
    r.x = 0;    r.y = 0;
    if (pixf->pixenum==CLUT4||pixf->pixenum==CLUT8) r.col = &c;
    else r.col = &colourtable[1];
    drawrect (videoram, &r, pixf, vids);

    r.x = width/2;    r.y = 0;
    if (pixf->pixenum==CLUT4||pixf->pixenum==CLUT8) c.r = 2;
    else r.col = &colourtable[2];
    drawrect (videoram, &r, pixf, vids);

    r.x = 0;    r.y = height/2;
    if (pixf->pixenum==CLUT4||pixf->pixenum==CLUT8) c.r = 3;
    else r.col = &colourtable[3];
    drawrect (videoram, &r, pixf, vids);

    r.x = width/2;    r.y = height/2;
    if (pixf->pixenum==CLUT4||pixf->pixenum==CLUT8) c.r = 0;
    else r.col = &colourtable[0];
    drawrect (videoram, &r, pixf, vids);
}

void usage(char *name){
     printf ("Usage: %s [options]\n"
        "Options: -f<pixelformat>\n"
        "            where format is one of:\n"
        "              CLUT4,CLUT8,ARGB1555,RGB565,ARGB\n"
        "         -s<width>x<heigth>\n"
        "            where width is either 720,640,360,320\n"
        "                  and height is either 288,240,480,576\n"
        "         -n\n"
        "            disables clearing the framebuffer after drawing\n"
        "            the testimage. This can be useful to keep the last\n"
        "            drawn image onscreen.\n"
        "\nExample: %s -fRGB322\n",name,name);
    exit(0);
}

int main (int argc,char **argv){
    struct fb_fix_screeninfo fix;
    struct fb_var_screeninfo var;
    struct fb_cmap cmap;
    struct rect r;
    int fbd;
    unsigned char *pfb;
    int stat;
    int optchar,fmode=-1,smode=-1,clear=1;
    int i_cmap,i_size,i_pix;
    extern char *optarg;
    
    if (argc!=0&&argc>4) usage(argv[0]);
    while ( (optchar = getopt (argc,argv,"f:s:n"))!= -1){
        int i,height,width;
        switch (optchar){
            case 'f':
                for (i=0;i<(sizeof(pixname)/sizeof(char*));i++){
                    if (!strncmp (optarg,pixname[i],strlen(pixname[i]))){
                        fmode=i;
                        printf ("displaying only %s-modes\n",pixname[i]);
                        break;
                    }
                }
                if (fmode==-1){
                    printf ("unknown pixelformat\n");
                    exit(0);
                }
                break;
            case 's':
                if (sscanf (optarg,"%dx%d",&width,&height)!=2){
                    printf ("parsing size failed\n");
                    exit(0);
                } else {
                    printf ("requested size %dx%d\n",width,height);
                    for (i=0;i<VIDSIZENUM;i++){
                        if (vidsizetable[i].width == width &&
                            vidsizetable[i].height == height){
                            smode = i;
                            break;
                        }
                    }
                    if (smode==-1){
                        printf ("this size is not supported\n");
                        exit(0);
                    }
                }
                break;
            case 'n':
                clear = 0;
                printf ("clearing framebuffer after drawing is disabled\n");
                break;
            case '?':
                usage (argv[0]);
        }
    }
    
    fbd = open (FBDEV, O_RDWR);
    if (fbd<0){
        perror ("Error opening framebuffer device");
        return 1;
    }
    stat = ioctl (fbd, FBIOGET_FSCREENINFO,&fix);
    if (stat<0){
        perror ("Error getting fix screeninfo");
        return 1;
    }
    stat = ioctl (fbd, FBIOGET_VSCREENINFO,&var);
    if (stat<0){
        perror ("Error getting var screeninfo");
        return 1;
    }
    stat = ioctl (fbd, FBIOPUT_VSCREENINFO,&var);
    if (stat<0){
        perror ("Error setting mode");
        return 1;
    }
    pfb = mmap (0, fix.smem_len, PROT_READ|PROT_WRITE, MAP_SHARED, fbd, 0);
    if (pfb == MAP_FAILED){
        perror ("Error mmap'ing framebuffer device");
        return 1;
    }

    // iterate over all modes
    for (i_pix=0;i_pix<PIXELFORMATNUM;i_pix++){
        if (fmode!=-1 && pixelformattable[i_pix].pixenum != fmode) continue;
        printf ("testing: %s",pixelformattable[i_pix].name);
        printf (" for sizes: \n");
        for (i_size=0;i_size<VIDSIZENUM;i_size++){
            if (smode!=-1 && i_size!=smode) continue;
            printf ("%dx%d ",vidsizetable[i_size].width,vidsizetable[i_size].height);
            if ((i_size%4)==3) printf ("\n");
            
            // try to set mode
            stat = setmode(fbd,&pixelformattable[i_pix],&vidsizetable[i_size]);
            if (stat==-2) perror ("fbtest: could not get fb_var-screeninfo from fb-device");
            else if (stat==-1){
                printf ("\nCould not set mode %s (%dx%d), possible reasons:\n"
                    "- you have a GTX (soz m8)\n"
                    "- your configuration does not have enough graphics RAM\n"
                    "- you found a bug\n"
                    "choose your poison accordingly...\n",
                    pixelformattable[i_pix].name,vidsizetable[i_size].width,vidsizetable[i_size].height);
                    continue;
            }
            // fill cmap;
            cmap.len = 1;
            if ((pixelformattable[i_pix].bpp==4)||
                ((pixelformattable[i_pix].bpp==8)&&(pixelformattable[i_pix].red.length!=3))){
                for (i_cmap=0;i_cmap<COLOURNUM;i_cmap++){
                    cmap.start=i_cmap;
                    cmap.red=&colourtable[i_cmap].r;
                    cmap.green=&colourtable[i_cmap].g;
                    cmap.blue=&colourtable[i_cmap].b;
                    cmap.transp=&colourtable[i_cmap].a;
                    stat = ioctl (fbd, FBIOPUTCMAP, &cmap);
                    if (stat<0) printf ("setting colourmap failed\n");
                }
            }
            // create the test image
            draw4field(pfb,&pixelformattable[i_pix],&vidsizetable[i_size]);
            usleep (500000);
            // clear screen
            if (clear){
                r.x=r.y=0;r.width = vidsizetable[i_size].width; r.height = vidsizetable[i_size].height;
                r.col = &colourtable[4];
                drawrect(pfb,&r,&pixelformattable[i_pix],&vidsizetable[i_size]);
            }
        }
        printf ("\n");
    }

    stat = munmap (pfb,fix.smem_len);
    if (stat<0){
        perror ("Error munmap'ing framebuffer device");
        return 1;
    }
    close (fbd);
    return 0;
}

shuffle
#include <iostream>
#include <cstdlib>   // for srand and rand
#include <ctime>     // for time
using namespace std;

int main() {
    int card[52];    // array of cards;
    int n;           // number of cards to deal
    srand(time(0));  // initialize seed "randomly"
     
    for (int i=0; i<52; i++) {
        card[i] = i;  // fill the array in order
    }
    
    while (cin >> n) {    
        //--- Shuffle elements by randomly exchanging each with one other.
        for (int i=0; i<(52-1); i++) {
            int r = i + (rand() % (52-i)); // Random remaining position.
            int temp = card[i]; card[i] = card[r]; card[r] = temp;
        }
        
        //--- Print first n cards as ints.
        for (int c=0; c<n; c++) {
            cout << card[c] << " ";  // Just print number
        }
        cout << endl;
    }
   
   return 0;
}

isinstring
bool IsInString(string strString, string strSubString)
{
    if(strString.length() <= 0 || strSubString.length() <= 0) return false;
    unsigned int index = strString.find(strSubString);
    if(index >= 0 && index < strString.length())
        return true;
    return false;
}

dv10-3
/************************************************
 * aufg10-3.c                                   *
 *                                              *
 * Sortieren eines char Feldes                  *
 * Bubble-Sort                                  *
 *                                              *
 * Autor: Philipp Karbach                       *
 * Datum: 15.05.08                              *
 ************************************************/
#include <stdio.h>
#include <string.h>

#define N 50

int main()
{ int n;  /* Anzahl der Feldelemente */
  char a[N][64];

  int i, j;/* Hilfsvariablen */
  char tmp[64];

  printf("Geben Sie eine Anzahl n <= %d und anschliessend n "
         "ganze Zahlen ein: ", N);
  scanf("%d", &n);

  gets(tmp);

  if ( n < 0 || n > N)
  { printf("Unzulaessige Eingabe: %d\n", n);
    return 1;
  }

  /* n Feldelemente lesen */
  for ( i = 0; i < n; ++i)
    gets(a[i]);

  /* Feldelemente unsortiert ausgeben */
  printf("gelesenen Feldelemente:\n");
  for ( i = 0; i < n; ++i)
    printf("%s ", a[i]);
  printf("\n");

  /* Feld der Groesse nach sortieren: 
   * groesstes Element nach ganz hinten,
   * zweitgroesstes an vorletzte Position usw.
   */ 
  for ( i = n-1; i > 0; --i)
    for ( j = 0; j < i; ++j)
      if ( strcmp(a[j], a[j+1]) ) 
      { 
    strcpy(tmp, a[j]);
    strcpy(a[j], a[j+1]);
    strcpy(a[j+1], tmp);
      }    

  /* Feldelemente sortiert ausgeben */
  printf("sortierte Feldelemente:\n");
  for ( i = 0; i < n; ++i)
    printf("%s ", a[i]);
  printf("\n");

  return 0;
}

Snippet Lister by Philipp Karbach © 2007