Sunday, May 25, 2014

How to convert UUID to String in Python!!!



              A universally unique identifier (UUID) is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE). Check here for more details.

             I recently faced a  scenario where I need to use string format of the UUID value. I searched in google and could not find proper answer. Finally I got the solution and here it is. After Creating a UUID, we can get different different values depending on the format. For example, we can get int, hex and byte values of UUID. Similarly using urn (Uniform resource name), we can get the string value of the UUID as shown below.

>>> uid = uuid.uuid1() #creating UUID
>>> uid 
UUID('52f8e1ba-e3ac-11e3-8232-a82066136178')
>>> uid.int #int format of UUID
110288963624339905056441828728831697272L
>>> uid.hex  #hexa format of UUID
'52f8e1bae3ac11e38232a82066136178'
>>> uid.bytes  #bytes format of UUID
'R\xf8\xe1\xba\xe3\xac\x11\xe3\x822\xa8 f\x13ax'
>>> uid.urn #uniform resource name
'urn:uuid:52f8e1ba-e3ac-11e3-8232-a82066136178'
>>> 

From the above example uid.urn returns string value 'urn:uuid:52f8e1ba-e3ac-11e3-8232-a82066136178'. But we need only value and we dont need first nine characters 'urn:uuid:', so we can skip those 9 characters to get the string value as shown below.

>>> uid_str = uid.urn
>>> str = uid_str[9:]
>>> str
'52f8e1ba-e3ac-11e3-8232-a82066136178'
>>> 

Happy Coding!!!

Thursday, May 1, 2014

Program to find binary value using bitwise operator in C!!!


/*************************************************
* This program finds the binary value of the given integer value
* Used bitwise operators to find binary value 
* Below is the logic to find binary value
* 1. Need to skip right most 0'1 until 1 comes 
* 2. After that, do AND operation with MASK value  print 1 on true else 0
* 3. Shift one bit left
* 4. Repeat step 2 Until Int size completes
*
*
* Int size is generally 4 bytes which is 32 bits
* MASK value for Int is in hexa (0x80000000)
* Above mask value is taken, because we need to mask Most significant bit (31st bit)
*
*************************************************/

#define INT_SIZE 32
#define MASK  (0x80000000) 
#include<stdio.h>
void findBinary(int num)
{
 int pos;
 int i=0;
 int flag = 0;
 
 //finding location from right side
 //so that we can ignore zeros
 //e.g: 0000100 same as 100, ignore 0000
 // ANDing 
 for(i=0;i<INT_SIZE;i++)
 {
  if(((num<<i) & MASK))
  {
   if(!flag)
   {
    pos = i;
    break;
   }
  }
 }
 printf("\nBinary value is ");
 for(i=pos;i<INT_SIZE;i++)
 {
  if(((num<<i) & MASK))
   printf("1");
  else
   printf("0");
 }
 printf("\n");

}
int main()
{
 int x = 0;
 printf("Enter input value\n");
 scanf("%d",&x);
 findBinary(x);
}
OutPut:
Enter input value
256
Binary value is 100000000

Enter input value
234
Binary value is 11101010

Happy Coding!!!

Popular Posts