How to separate last two bits of a byte?

edited April 2017 in How To...

I am aware that there are many approcahes to removing something from a string, like

String test = "this one is simple. (" test = test.replaceAll(" (", "");

Or something along those lines. Now, if I want to create two strings, or integers, from a single byte, with one being the last two bits, and the other one the rest, how could I do it? For example: I have 10100110, and I want to make code to create "101001" and "10", as the output, without using code like "find 10 and split it", since I want to be able to use it for the binary values of a pixel. I hope there is a function for this.

Is it even possible?

Tagged:

Answers

  • Answer ✓

    Use substring(). Example:

    String cat = "meeeow";
    
    println(cat.substring(0,cat.length()-2));
    println(cat.substring(cat.length()-2, cat.length()));
    println("");
    
    cat = "100100";
    
    println(cat.substring(0,cat.length()-2));
    println(cat.substring(cat.length()-2, cat.length()));
    println("");
    
    byte num = byte(178);
    
    cat = "" + binary(num);
    
    println(cat.substring(0,cat.length()-2));
    println(cat.substring(cat.length()-2, cat.length()));
    println("");
    
  • Great! Thanks!

  • if I want to create two strings, or integers, from a single byte, with one being the last two bits

    Just to clarify, you are working with two bytes? Or you are receiving a stream of bytes which you are processing in String format, like "10001011"?

    If we stcik to this example: https://processing.org/reference/libraries/serial/Serial_readBytes_.html

    byte[] inBuffer = new byte[7];

    Then I want to create an integer based on the last two bits of inBuffer[0] and the bits in inBuffer[1]. I will do:

    int val=0;
    byte[] inBuffer = new byte[2];
    
    inBuffer[0]=0; 
    inBuffer[1]='a';    
    val = ((inBuffer[0]&0x03)<< 8) | inBuffer[1];    
    println(val);
    

    0x03 is used to extract the last two bits in the first field. For bit shifting, check:

    Check: https://processing.org/reference/leftshift.html

    Kf

  • I am reading the 32- bit value of argb values for an image pixel, which I have already separated into single bytes.

  • edited April 2017

    @WowStudios

    I am reading the 32- bit value of argb values for an image pixel, which I have already separated into single bytes.

    If you'we done that it's just val & 3 for the last two bits,
    & is bitwise AND ,
    0x03 = 3 = 00000011

    if you want the first 6 bits use firstsix = val&252 , or val-(val&3);
    You may need to bitshift the result by two , >> 2 , depending on what you're using the number for

Sign In or Register to comment.