MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


Thus, to retrieve a value from the byte stream, you must read one byte at a time shifting each byte into
position. That is, you read the first byte and then the second, shifting it to the left and adding the first byte.
Think of it this way: there are two bytes in an integer and you are splitting them. To reconstruct the integer,
you have to take the first byte (the leftmost bits) and shift it 8 bits to the left. This leaves the rightmost byte
empty. An illustration follows. I use hexadecimal values to keep the example easy to read.


Integer: 0x5AFE
Left-most byte: 0x5A
Right-most byte: 0xFE
Left-most byte shifted: 0x5A << 8 = 0x5A00
Adding in the right most byte: 0x5A00 + 0x00FE = 0x5AFE


Similarly, storing the integer requires shifting the leftmost byte to the right to preserve the values. I
leave this for you to explore as an exercise. Listing 4-7 shows two methods for reading and storing integer
values in a byte buffer. Take some time to read through these should you need to read or store integers in a
byte stream.


Listing 4-7. Reading and Storing Integers in a Byte Array


/**



  • get_lcb_len - Retrieves the length of a length coded binary value



  • This reads the first byte from the offset into the buffer and returns

  • the number of bytes (size) that the integer consumes. It is used in

  • conjunction with read_int() to read length coded binary integers

  • from the buffer.



  • Returns integer - number of bytes integer consumes
    */
    int get_lcb_len(byte buffer[], int offset) {
    int read_len = buffer[offset];
    if (read_len > 250) {
    // read type:
    byte type = buffer[offset+1];
    if (type == 0xfc)
    read_len = 2;
    else if (type == 0xfd)
    read_len = 3;
    else if (type == 0xfe)
    read_len = 8;
    }
    return 1;
    }
    /**

  • read_int - Retrieve an integer from the buffer in size bytes.



  • This reads an integer from the buffer at offset position indicated for

  • the number of bytes specified (size).



  • buffer[in] byte stream in memory

  • offset[in] offset from start of buffer

  • size[in] number of bytes to use to store the integer

Free download pdf