Friday, March 18, 2011

Setting a Bit Pattern

Here's some code that will set the bits of a variable to a specified pattern.  It does not require any external libraries to be used.

void SetBitPattern(unsigned int& V, const char* pattern, int startBitIndex){
  int len;
  for(len = 0 ; pattern[len] ; len++);
  for(len = (startBitIndex + len - 1) ; 
    *pattern ;
    V = (*pattern - '0' ? (V | (1<<len)) : (V & ~(1<<len))), pattern++ , len--);
}

Tuesday, January 25, 2011

Making an int into a char* (string) Part 2.1

I realized afterwards that I forgot to ensure my function would work with negative numbers as well as positive.  I have added a few lines to remedy this.

int my_itoa(char* str, int num) {
  int i, neg = 0, length = 1, x = 0;
  
  if(str != NULL) {
    if(num < 0) {
      neg = num;
      num = -num;
    }
    for(i = num / 10; i > 0 ; i /= 10) {
      length++;
    }
    for(i = length - 1; i >= 0; i--) {
      if(neg < 0) {
        str[0] = '-';
        neg = 1;
      }
      str[i + neg] = (num % 10) + '0';
      num /= 10;
    }
    str[length + neg] = '\0';
    x = 1;
  }
  return x;
}

Making an int into a char* (string) Part 2

Well, I've got it.  Turns out what I had before isn't probably the best way to code a function for that, since C apparently doesn't like functions returning char* and will refuse to work right if you do.

So here we have a function that requires both the integer holding the number and the string that the number is to be inserted into as parameters. It will return 1 if it was successful and 0 if it wasn't.

int my_itoa(char* str, int num) {
  int i, digit, neg = 0, length = 1, x = 0;
 
  if(str != NULL) {
    if(num < 0) {
      neg = num;
      num = -num;
    }
    for(i = num / 10; i > 0 ; i /= 10) {
      length++;
    }
    for(i = length - 1; i >= 0; i--) {
      if(neg < 0) {
        str[0] = '-';
        neg = 1;
      }
      digit = num % 10;
      str[i + neg] = digit + '0';
      num /= 10;
    }
    str[length + neg] = '\0';
    x = 1;
  }
  return x;
}
 Because I didn't want the function to require any libraries, all it can really check for is if the char* pointer is actually pointing to something.

Making an int into a char* (string) Part 1

I need to make a function that will convert an integer into a c string.  Now, if it hadn't been shown in class, I would have just used the following:

const char* my_itoa(int x) {
  static char c[21];
  sprintf(c,"%d", x);
  return c;
}

But since it has, I essentially have to code what sprintf() is doing from scratch.

Hey

Just making sure I know how this thing works.