1. Си / Говнокод #13467

    +132

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    #define max    0x08         //Max number of samples to average/filter
    #define byte unsigned char
    #define word unsigned int
    #define dword unsigned long
    
    #define FILTER 0
    #define AVG 1
    
    typedef struct  {
      word  reading[max];
      word  result[max];
    } ResultStct;
    
    
    static ResultStct x;
    static char samp = 0;//filter;
    const byte filter_mode = FILTER;
    
    extern int avg_result;
    
    void MYfilter(word input_sample) 
    {
      byte j;
      dword X;
        
    	x.reading[samp] = input_sample;
      
    	if(samp>0){
    
    		X=0;
    		for (j=0;j<=samp;j++){
    		  X += x.reading[j];
    		}
    		avg_result = (X >> 3) - 0x0200;
    		
    	} 
       
    	// Shift array of results if we hit max
    	if (samp >= max-1) {
    		for (j=0;j<max-1;j++){
    			x.result[j]  = x.result[j+1];
    			x.reading[j] = x.reading[j+1];
    		}
    		samp = max-1;
    	}
    	else 
    	{
    		samp++;
    	} //end if (i => max)

    Такой вот МОЩНЕЙШИЙ фильтр встретился в одном проекте.

    _113, 24 Июля 2013

    Комментарии (18)
  2. Си / Говнокод #13461

    +134

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    #include <inttypes.h>
    
    union Str
    {
       uint64_t a;
       char  str[8];
    };
    
    int main(void)
    {
      union Str str;
      memcpy( &str.str, "12345678", sizeof(str.a));
    
    
    str.a = ((str.a & 0x0F000F000F000F00)>>8) +
            ((str.a & 0x000F000F000F000F)*10);
    
    str.a = 1000000 * ((str.a >> 0 ) & 0xFF) +
              10000 * ((str.a >> 16) & 0xFF) +
                100 * ((str.a >> 32) & 0xFF) +
                      ((str.a >> 48) & 0xFF);
    //little-endian only. Можно переделать под big-endian
    
    printf("%"PRIu64, str.a);
    
    return 0;
    }

    Байтоебское преобразование строки из 8 цифр(в виде ascii символов) в число

    j123123, 21 Июля 2013

    Комментарии (10)
  3. Си / Говнокод #13443

    +138

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    uint32_t multiply (uint16_t a, uint16_t b)
    {
      return ((a &  ( (int16_t)( ( b & (1 << 0) ) << 15 ) ) / ( 1 << 15) ) << 0 ) +
             ((a &  ( (int16_t)( ( b & (1 << 1) ) << 14 ) ) / ( 1 << 15) ) << 1 ) +
             ((a &  ( (int16_t)( ( b & (1 << 2) ) << 13 ) ) / ( 1 << 15) ) << 2 ) +
             ((a &  ( (int16_t)( ( b & (1 << 3) ) << 12 ) ) / ( 1 << 15) ) << 3 ) +
             ((a &  ( (int16_t)( ( b & (1 << 4) ) << 11 ) ) / ( 1 << 15) ) << 4 ) +
             ((a &  ( (int16_t)( ( b & (1 << 5) ) << 10 ) ) / ( 1 << 15) ) << 5 ) +
             ((a &  ( (int16_t)( ( b & (1 << 6) ) << 9  ) ) / ( 1 << 15) ) << 6 ) +
             ((a &  ( (int16_t)( ( b & (1 << 7) ) << 8  ) ) / ( 1 << 15) ) << 7 ) +
             ((a &  ( (int16_t)( ( b & (1 << 8) ) << 7  ) ) / ( 1 << 15) ) << 8 ) +
             ((a &  ( (int16_t)( ( b & (1 << 9) ) << 6  ) ) / ( 1 << 15) ) << 9 ) +
             ((a &  ( (int16_t)( ( b & (1 <<10) ) << 5  ) ) / ( 1 << 15) ) << 10) +
             ((a &  ( (int16_t)( ( b & (1 <<11) ) << 4  ) ) / ( 1 << 15) ) << 11) +
             ((a &  ( (int16_t)( ( b & (1 <<12) ) << 3  ) ) / ( 1 << 15) ) << 12) +
             ((a &  ( (int16_t)( ( b & (1 <<13) ) << 2  ) ) / ( 1 << 15) ) << 13) +
             ((a &  ( (int16_t)( ( b & (1 <<14) ) << 1  ) ) / ( 1 << 15) ) << 14) +
             ((a &  ( (int16_t)( ( b & (1 <<15) ) << 0  ) ) / ( 1 << 15) ) << 15);
    }

    Умножение двух чисел через битовые маски и сдвиги без условных переходов. Компилятор переведет деление инта на сдвинутую единчку в арифметический сдвиг
    Использование ">>" применительно к signed типам - implementation defined http://stackoverflow.com/questions/4009885/arithmetic-bit-shift-on-a-signed-integer/4009922

    j123123, 18 Июля 2013

    Комментарии (18)
  4. Си / Говнокод #13430

    +141

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    /* common /constants/ */
    double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3,
           dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4,
           dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt,
           ce[5][13], dxmax, dymax, dzmax, xxcon1, xxcon2,
           xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1,
           dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4,
           yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1,
           zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1,
           dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1,
           dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2,
           c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt,
           dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1,
           c2dtty1, c2dttz1, comz1, comz4, comz5, comz6,
           c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16;

    делов-то, "обычные" константы...

    NAS Parallel Benchmark

    Noname01, 16 Июля 2013

    Комментарии (11)
  5. Си / Говнокод #13422

    +126

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    typedef struct {
      uint32_t id;
      char * title;
    } dbrow_t;
    
    typedef struct {
      char * context;
      dbrow_t dbrow;
    } parser_context_t;
    
    typedef enum {    
      bad_char = 0,
      identifer,
      number,
      state_end_context,  
      state_end_line
    } type_t;
    
    type_t ch_d[0x100] = { [0] = state_end_line, [1 ... 0xff] = bad_char, ['0' ... '9'] = number, ['a' ... 'z'] = identifer, ['\n'] = state_end_context};
    
    inline char * do_other_type(char * p, type_t type) { while(ch_d[*(++p)] == type); return p;}
    
    static inline uint64_t bad_char_headler(parser_context_t * context) { context->context = do_other_type(context->context, bad_char); return 1;}
    
    static inline uint64_t number_headler(parser_context_t * context) {
      uint32_t id = 0; char * p = context->context;
      while(({ id *= 10; id += (*p - '0'); ch_d[*(++p)];}) == number);
      context->dbrow.id = id; context->context = p;
      return 1;
    }
    
    static inline uint64_t identifer_headler(parser_context_t * context) {
      char * p = context->context, * title = context->dbrow.title;
      char * end_identifer = do_other_type(p, identifer);
      memcpy(title, p, (end_identifer - p)); *(title + (end_identifer - p)) = 0;
      context->context = end_identifer;
      return 1;
    }
    
    static inline uint64_t end_context_headler(parser_context_t * context) {
      context->context = do_other_type(context->context, state_end_context);
      if(context->dbrow.id && *context->dbrow.title)
        fprintf(stderr, "id = %u, title = %s\n", context->dbrow.id, context->dbrow.title);
      context->dbrow.id = 0, *context->dbrow.title = 0;
      return 1;
    }
    
    static inline uint64_t end_line_headler(parser_context_t * context) { return 0; }
    
    typedef uint64_t(*headler_ptr_t)(parser_context_t *);
    
    headler_ptr_t headlers[] = { [bad_char] = bad_char_headler, [identifer] = identifer_headler, [number] = number_headler, [state_end_context] = end_context_headler, [state_end_line] = end_line_headler };
    
    int main(void) {
        char * content = strcpy(malloc(50), "1|raz\n11|dva\n21|tri\n31|shestb\n5000|test\n|||\n||\n|\n");
        parser_context_t context = (parser_context_t){ .context = content, .dbrow = (dbrow_t){ .title = malloc(1000)}};
        while(headlers[ch_d[*(context.context)]](&context));
        return 0;
    }

    Решил пацанам показать как писать парсер - вышло говно. Хотя так-то должно тащить - забенчите кто-нибудь, настолько это гумно медленнее strtok()'а.

    superhackkiller1997, 15 Июля 2013

    Комментарии (144)
  6. Си / Говнокод #13416

    +129

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    void swap (char *x, char *y)
    {
        char temp;
        temp = *x;
        *x = *y;
        *y = temp;
    }
     
    void permute(char *a, int i, int n)
    {
        int j;
        if (i == n)
        printf("%s\n", a);
        else
        {
            for (j = i; j <= n; j++)
            {
                swap((a+i), (a+j));
                permute(a, i+1, n);
                swap((a+i), (a+j));
            }
        }
    }
     
     
    int main()
    {
        char str[80] ;
        int len=0,i;
        puts("Enter a string:\n\n");
        gets(str);
        for (i=0; str[i] != '\0'; i++)
        {
            len++;
        }
        permute(str, 0, len);
        getchar();
        return 0;
    }

    Источник:
    http://www.c-program-example.com/2012/04/c-program-to-find-all-permutations-of.html

    про strlen видимо никто не слышал

    denis90, 13 Июля 2013

    Комментарии (125)
  7. Си / Говнокод #13408

    +123

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    #include <malloc.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdint.h>
    
    typedef struct {
      char * begin;
      uint64_t size, data_size;
    } str_t;
    
    inline uint64_t max(uint64_t a, uint64_t b) {
      return (a > b) ? a : b;
    }
    
    inline str_t correct_data_size(str_t str, uint64_t new_size) {
      if(str.data_size < new_size) {
        str.data_size = (max(str.data_size, new_size) << 1);
        str.begin = realloc(str.begin, str.data_size);    
      }
      return str;
    }
    
    inline str_t concat(str_t dest, str_t src) {
      uint64_t new_size = (dest.size + src.size - 1);
      dest = correct_data_size(dest, new_size);
      memcpy((dest.begin + dest.size - 1), src.begin, src.size);
      dest.size = new_size;
      return dest;
    }
    
    inline str_t create_str(char * str, uint64_t size) {
      return (str_t){.begin = strcat(malloc(size), str), .size = size, .data_size = size};
    }
    
    inline void print_str_t(str_t str) {
      fprintf(stderr, "str = %ssize = %lu, data_size = %lu\n", str.begin, str.size, str.data_size);
    }
    
    uint64_t test(uint64_t star_n, uint64_t n, str_t str, str_t * gstr) {
      uint64_t end = (star_n + n);
      do {
        *gstr = concat(*gstr, str);
        
        char * pos = gstr->begin;
        while((pos = strstr(pos, "efgh")))
          memcpy(pos,"____",4);
        
      } while((++star_n) != end);
      return star_n;
    }
    
    int main(void) {
      char data[] = "abcdefghefghefgh";
      str_t str = create_str(data, sizeof(data)); 
      str_t gstr = create_str("", 1);
      time_t starttime = time(NULL);
      
      uint64_t block_c = 0;
      
      while((block_c = test(block_c, ((256/16) * 1024), str, &gstr)) != (((256/16) * 1024) * 20))
        printf("%ldsec\t\t%lukb\n",time(NULL)-starttime,gstr.size/1024);
      
    }

    Минимально оптимизированный вариант в царь-стиле теста из предыдущего ГК. Никто не увидел и начали на меня кукарекать. То ещё ГК, давайте объясняйте что здесь говно.

    superhackkiller1997, 11 Июля 2013

    Комментарии (129)
  8. Си / Говнокод #13405

    +126

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    
    int main(){
    
    setbuf(stdout,NULL); //disable output buffering
    
    char *str=malloc(8);
    strcpy(str,"abcdefgh");
    
    str=realloc(str,strlen(str)+8);
    strcat(str,"efghefgh");     //sprintf(str,"%s%s",str,"efghefgh");
    
    int imax=1024/strlen(str)*1024*4;
    
    printf("%s","exec.tm.sec\tstr.length\n"); //fflush(stdout);
    
    time_t starttime=time(NULL);
    char *gstr=malloc(0);
    int i=0;
    char *pos;
    int lngth;
    
    char *pos_c=gstr;
    int str_len=strlen(str);
    
        while(i++ < imax+1000){
            lngth=strlen(str)*i;
            gstr=realloc(gstr,lngth+str_len);
            strcat(gstr,str);    //sprintf(gstr,"%s%s",gstr,str);
            pos_c+=str_len;
    
            pos=gstr;
            while(pos=strstr(pos,"efgh")){
                memcpy(pos,"____",4);
            }
    
            if(lngth % (1024*256)==0){
                printf("%dsec\t\t%dkb\n",time(NULL)-starttime,lngth/1024); //fflush(stdout);
            }
        }
    //printf("%s\n",gstr);
    
    }

    http://raid6.com.au/~onlyjob/posts/arena/ - банальый пример бенчмарков всяких недоЯП. Это новый топ10 шедевр на этот месяц.

    Именно про такие бенчи кукарекают питушки, когда ссылаются на какие-то бенчи - самое смешно в этом то, что %подставить имя ЯП% сравнивать с сишкой бесполезно, ибо их стдлиб написана на Си и дрёглает либц. Т.е. сравнивая стдлиб разных ЯП - вы сравниваете сишные реализации и оверхеды самих ЯП.

    superhackkiller1997, 11 Июля 2013

    Комментарии (174)
  9. Си / Говнокод #13396

    +132

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    Дорогой участник! Не спеши покидать страницу. Я прошу тебя помочь:
    не поленись, пройдись по всем постам, и поставь каждому участнику по минусу;
    минусуя других участников ты воспитываешь в себе чувство меры и помогаешь обществу снижать ЧСВ. 
    Заранее спасибо, друг мой. Ты будешь вознагражден за это деяние!
    
    Тот, кто покинул страницу, но не выполнил моей просьбы, умрет через 9 дней.

    Дорогой участник! Не спеши покидать страницу. Я прошу тебя помочь:
    не поленись, пройдись по всем постам, и поставь каждому участнику по минусу;
    минусуя других участников ты воспитываешь в себе чувство меры и помогаешь обществу снижать ЧСВ.
    Заранее спасибо, друг мой. Ты будешь вознагражден за это деяние!


    Тот, кто покинул страницу, но не выполнил моей просьбы, умрет через 9 дней.

    Stertor, 11 Июля 2013

    Комментарии (0)
  10. Си / Говнокод #13358

    +131

    1. 1
    2. 2
    3. 3
    int rotate(int a, int k) {
        return (a << k) | (a >> (32-k));
    }

    Вращение на k бит влево.

    bormand, 10 Июля 2013

    Комментарии (73)