Skip to content

byteSlice()

2010 April 30
by Tedb0t

Here’s a weird little function I just wrote to “slice” an integer out of a byte:

int byteSlice(byte input, byte startIndex, byte endIndex){
  
  // generates an integer value from an arbitrary slice of a byte
  // Example:
  //
  // index:   01234567
  // input = B01101100 (int 108)
  //
  // startIndex = 1
  // endIndex = 4
  // slice = B1101
  // returns int 13
  
  byte output;
  
  // shift left to shave off bits before startIndex
  output = input << startIndex;
  // shift right to shave off bits after endIndex
  output = output >> (7-endIndex) + startIndex;

  return int(output);
}

This basically takes out a chunk of a byte and gives you the integer representation of its bits.  The input index byte datatypes are a neurotic memory optimization, since the indices can’t be greater than 7. 😉 Example Arduino implementation:

void setup(){
  
  Serial.begin(9600);
  byte in = 108;
  
  Serial.print(in, DEC);
  Serial.print("\t");
  Serial.println(in, BIN);
  Serial.println("----------------");
  Serial.print(byteSlice(in, 0, 7), DEC);
  Serial.print("\t");
  Serial.println(byteSlice(in, 0, 7), BIN);
  Serial.println("----------------");
  Serial.print(byteSlice(in, 1, 4), DEC);
  Serial.print("\t");
  Serial.println(byteSlice(in, 1, 4), BIN);
  Serial.println("----------------");
  Serial.print(byteSlice(in, 3, 6), DEC);
  Serial.print("\t");
  Serial.println(byteSlice(in, 3, 6), BIN);
}

void loop(){
}

Related Posts:


Comments are closed.