utility string functions

convert string into binary representation (8 bits per char)

split string into chars, for each char get ordinal number, and create string using 8bit  format of the number. Concat all

def str_2_binrep(s):
  return "".join(['{0:008b}'.format(ord(c)) for c in list(s)])

example:

>>> str_2_binrep("Hello World")
'0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100'

If you want to have a space in between, just write

'{0:008b} '

instead.

split string into groups of n characters

fill array with substrings, range(start, stop, stepwidth)

def str_splitintogroups(s, n):
  return [s[i : (i+n) ] for i in range(0, len(s), n)]

example:

>>> str_splitintogroups("split string into groups", 3)
['spl', 'it ', 'str', 'ing', ' in', 'to ', 'gro', 'ups']

XOR of two strings

zip builds tuples containing the ith char of each string; for each pair the xor of the octal number of the char is converted into char and appended

def str_xor(s1, s2):
  return "".join([chr( ord(c1) ^ ord(c2) ) for (c1,c2) in zip(s1, s2)])

example:

>>> str_xor("Hello", "World")
'\x1f\n\x1e\x00\x0b'

>>> str_xor("Hello", "Hello")
'\x00\x00\x00\x00\x00'

Encode String as hex, and decode back

String encode, see http://docs.python.org/2/library/codecs.html#standard-encodings for possible encodings (python 2); output is using 2 digits each per byte of input

example:

>>> "BibiBlocksberg".encode('hex')
'42696269426c6f636b7362657267'

>>> "BibiBlocksberg".encode('hex').decode('hex')
'BibiBlocksberg'

Dec to Hex, Hex to Dec

How to convert a decimal number into a hex representation:

examples:

>>> hex(1000)
'0x3e8'

>>> "%X"%1000
'3E8'

How to convert a from hex (or other) back to decimal representation:

examples:

>>> int("3E8", 16)
1000

>>> int("1001", 2)
9

How to receive and parse a JSON array

Situation:
You got some (client) application, that needs data from a mysql database.
The application cannot connect to the database itself. It sends a HTTP GET/POST request to a webserver, that gets the data out of the mysql database and packs it into a JSON Array. This JSON Array is sent back to the client.

The client receives the JSON Array and parses it.

This is the php code for the webserver (inspired from )

	
/**
 * download list of registered users from server at cmd.eyedbits.com
 * 
 * @return list of users
 */
static Vector<String> downloadUserList() {
  Log.i(TAG, String.format("Downloading UserList"));
  
  String serverUrl = SERVER_URL + SERVER_URL_QUERYUSERLIST;

  //TODO: implement multiple tries with exponential backoff if server is not responding		
  DefaultHttpClient hc = new DefaultHttpClient();
  ResponseHandler <String> res = new BasicResponseHandler();
  HttpGet getMethod = new HttpGet(serverUrl);

  Vector<String> retVector = new Vector<String>(); 
  try {
    String response = hc.execute(getMethod, res);
    Log.i(TAG, "Http response: " + response);
    // todo check if successfull and not error
    
    // parse string
    try {
      JSONArray jsonArray = new JSONArray(response);
      for (int i = 0; i < jsonArray.length(); ++i) {
        JSONObject row = jsonArray.getJSONObject(i);
        String userName = row.getString("UserName");
        retVector.add(userName);
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  
  return retVector;
}

How to expose data from a mysql database via php/JSON for access via HTTP

Situation:
You got some (client) application, that needs data from a mysql database.
The application cannot connect to the database itself. It sends a HTTP GET/POST request to a webserver, that gets the data out of the mysql database and packs it into a JSON Array. This JSON Array is sent back to the client.

(Follow up situation, the client has to request and parse the data)

What you need:

– mysql database
– webserver with php

This is the php code for the webserver (inspired from )

<?php
  // connect to Database
  // database specifications, adapt your configuration
  $dbUri = "...";
  $dbUser = "...";
  $dbPassword = "...";
  $dbDatabaseName = "...";

  // establish connection
  $db = mysql_connect($dbUri, $dbUser, $dbPassword) OR
        die(mysql_error());

  mysql_select_db($dbDatabaseName, $db) OR
        die(mysql_error());

  // example query, adapt to your needs
  $sqlquery = "SELECT ... FROM ... WHERE ... ORDER BY ... ASC;";
  
  $result = mysql_query($sqlquery) OR
        die(mysql_error());
  
  if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
  } else {
    $rows = array();
    // fill array
    while($r = mysql_fetch_assoc($result)) {
        $rows[] = $r;
    }
    // encode array as JSON and print it
    print json_encode($rows);
  }
?>