Posted By

mwb1100 on 10/30/09


Tagged

domain public


Versions (?)

strings.h implementation


 / Published in: C
 

Implementation of the functions in the old Unix <strings.h> header. Public domain.

  1. #include <string.h>
  2. #include <ctype.h>
  3. #include <strings.h>
  4.  
  5. int bcmp( void const* p1, void const* p2, size_t n)
  6. {
  7. return memcmp( p1, p2, n);
  8. }
  9.  
  10. void bcopy( void const* src, void* dst, size_t n)
  11. {
  12. memmove( dst, src, n);
  13. }
  14.  
  15. void bzero( void* p, size_t n)
  16. {
  17. memset( p, 0, n);
  18. }
  19. char* index( char const* s, int c)
  20. {
  21. return strchr( s, c);
  22. }
  23.  
  24.  
  25. char* rindex( char const* s, int c)
  26. {
  27. return strrchr( s, c);
  28. }
  29.  
  30. int strcasecmp( char const* s1, char const* s2)
  31. {
  32. for (;;) {
  33. int c1 = tolower( *((unsigned char*) s1++));
  34. int c2 = tolower( *((unsigned char*) s2++));
  35.  
  36. if ((c1 != c2) || (c1 == '\0')) {
  37. return( c1 - c2);
  38. }
  39. }
  40. }
  41.  
  42. int strncasecmp( char const* s1, char const* s2, size_t n)
  43. {
  44. for (; n != 0; --n) {
  45. int c1 = tolower( *((unsigned char*) s1++));
  46. int c2 = tolower( *((unsigned char*) s2++));
  47.  
  48. if ((c1 != c2) || (c1 == '\0')) {
  49. return( c1 - c2);
  50. }
  51. }
  52.  
  53. return( 0);
  54. }
  55.  
  56.  
  57. int ffs(int v)
  58. {
  59. unsigned int x = v;
  60. int c = 1;
  61.  
  62. /*
  63.   * adapted from from
  64.   * http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightBinSearch
  65.   *
  66.   * a modified binary search algorithm to count 0 bits from
  67.   * the right (lsb). This algorithm should work regardless
  68.   * of the size of ints on the platform.
  69.   *
  70.   */
  71.  
  72. /* a couple special cases */
  73. if (x == 0) return 0;
  74. if (x & 1) return 1; /* probably pretty common */
  75.  
  76. c = 1;
  77. while ((x & 0xffff) == 0) {
  78. x >>= 16;
  79. c += 16;
  80. }
  81. if ((x & 0xff) == 0) {
  82. x >>= 8;
  83. c += 8;
  84. }
  85. if ((x & 0x0f) == 0) {
  86. x >>= 4;
  87. c += 4;
  88. }
  89. if ((x & 0x03) == 0) {
  90. x >>= 2;
  91. c += 2;
  92. }
  93.  
  94. c -= (x & 1);
  95. c += 1; /* ffs() requires indexing bits from 1 */
  96. /* ie., the lsb is bit 1, not bit 0 */
  97. return c;
  98. }

Report this snippet  

You need to login to post a comment.