]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
COMP: on win32 sintrgs.h does not exist
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/06 19:20:23 $
7   Version:   $Revision: 1.75 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmUtil.h"
20 #include "gdcmDebug.h"
21
22 // For GetCurrentDate, GetCurrentTime
23 #include <time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26
27 #include <stdarg.h>  //only included in implementation file
28 #include <stdio.h>   //only included in implementation file
29
30 #if defined(_MSC_VER)
31    #include <winsock.h>  // for gethostname & gethostbyname
32    #undef GetCurrentTime
33 #else
34 #ifndef __BORLANDC__
35    #include <unistd.h>  // for gethostname
36    #include <netdb.h>   // for gethostbyname
37 #endif
38 #endif
39
40 namespace gdcm 
41 {
42 /**
43  * \ingroup Globals
44  * \brief Provide a better 'c++' approach for sprintf
45  * For example c code is:
46  * sprintf(trash, "%04x|%04x", group , element);
47  *
48  * c++ is 
49  * std::ostringstream buf;
50  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
51  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
52  *     << std::hex <<  element;
53  * buf.str();
54  */
55
56 std::string Util::Format(const char* format, ...)
57 {
58    char buffer[2048];
59    va_list args;
60    va_start(args, format);
61    vsprintf(buffer, format, args);  //might be a security flaw
62    va_end(args); // Each invocation of va_start should be matched 
63                  // by a corresponding invocation of va_end
64                  // args is then 'undefined'
65    return buffer;
66 }
67
68
69 /**
70  * \ingroup Globals
71  * \brief Because not available in C++ (?)
72  */
73 void Util::Tokenize (const std::string& str,
74                      std::vector<std::string>& tokens,
75                      const std::string& delimiters)
76 {
77    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
78    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
79    while (std::string::npos != pos || std::string::npos != lastPos)
80    {
81       tokens.push_back(str.substr(lastPos, pos - lastPos));
82       lastPos = str.find_first_not_of(delimiters, pos);
83       pos     = str.find_first_of    (delimiters, lastPos);
84    }
85 }
86
87 /**
88  * \ingroup Globals
89  * \brief Because not available in C++ (?)
90  *        Counts the number of occurences of a substring within a string
91  */
92  
93 int Util::CountSubstring (const std::string& str,
94                           const std::string& subStr)
95 {
96    int count = 0;   // counts how many times it appears
97    std::string::size_type x = 0;       // The index position in the string
98
99    do
100    {
101       x = str.find(subStr,x);       // Find the substring
102       if (x != std::string::npos)   // If present
103       {
104          count++;                  // increase the count
105          x += subStr.length();     // Skip this word
106       }
107    }
108    while (x != std::string::npos);  // Carry on until not present
109
110    return count;
111 }
112
113 /**
114  * \ingroup Globals
115  * \brief  Weed out a string from the non-printable characters (in order
116  *         to avoid corrupting the terminal of invocation when printing)
117  * @param s string to remove non printable characters from
118  */
119 std::string Util::CreateCleanString(std::string const & s)
120 {
121    std::string str = s;
122
123    for(unsigned int i=0; i<str.size(); i++)
124    {
125       if(!isprint((unsigned char)str[i]))
126       {
127          str[i] = '.';
128       }
129    }
130
131    if(str.size() > 0)
132    {
133       if(!isprint((unsigned char)s[str.size()-1]))
134       {
135          if(s[str.size()-1] == 0)
136          {
137             str[str.size()-1] = ' ';
138          }
139       }
140    }
141
142    return str;
143 }
144
145 /**
146  * \ingroup Globals
147  * \brief   Add a SEPARATOR to the end of the name is necessary
148  * @param   pathname file/directory name to normalize 
149  */
150 std::string Util::NormalizePath(std::string const & pathname)
151 {
152    const char SEPARATOR_X      = '/';
153    const char SEPARATOR_WIN    = '\\';
154    const std::string SEPARATOR = "/";
155    std::string name = pathname;
156    int size = name.size();
157
158    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
159    {
160       name += SEPARATOR;
161    }
162    return name;
163 }
164
165 /**
166  * \ingroup Globals
167  * \brief   Get the (directory) path from a full path file name
168  * @param   fullName file/directory name to extract Path from
169  */
170 std::string Util::GetPath(std::string const & fullName)
171 {
172    std::string res = fullName;
173    int pos1 = res.rfind("/");
174    int pos2 = res.rfind("\\");
175    if( pos1 > pos2)
176    {
177       res.resize(pos1);
178    }
179    else
180    {
181       res.resize(pos2);
182    }
183
184    return res;
185 }
186
187 /**
188  * \ingroup Util
189  * \brief   Get the (last) name of a full path file name
190  * @param   fullName file/directory name to extract end name from
191  */
192 std::string Util::GetName(std::string const & fullName)
193 {   
194   std::string filename = fullName;
195
196   std::string::size_type slash_pos = filename.rfind("/");
197   std::string::size_type backslash_pos = filename.rfind("\\");
198   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
199   if(slash_pos != std::string::npos)
200     {
201     return filename.substr(slash_pos + 1);
202     }
203   else
204     {
205     return filename;
206     }
207
208
209 /**
210  * \ingroup Util
211  * \brief   Get the current date of the system in a dicom string
212  */
213 std::string Util::GetCurrentDate()
214 {
215     char tmp[512];
216     time_t tloc;
217     time (&tloc);    
218     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
219     return tmp;
220 }
221
222 /**
223  * \ingroup Util
224  * \brief   Get the current time of the system in a dicom string
225  */
226 std::string Util::GetCurrentTime()
227 {
228     char tmp[512];
229     time_t tloc;
230     time (&tloc);
231     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
232     return tmp;  
233 }
234
235 /**
236  * \brief Create a /DICOM/ string:
237  * It should a of even length (no odd length ever)
238  * It can contain as many (if you are reading this from your
239  * editor the following character is is backslash followed by zero
240  * that needed to be escaped with an extra backslash for doxygen) \\0
241  * as you want.
242  */
243 std::string Util::DicomString(const char* s, size_t l)
244 {
245    std::string r(s, s+l);
246    assert( !(r.size() % 2) ); // == basically 'l' is even
247    return r;
248 }
249
250 /**
251  * \ingroup Util
252  * \brief Create a /DICOM/ string:
253  * It should a of even lenght (no odd length ever)
254  * It can contain as many (if you are reading this from your
255  * editor the following character is is backslash followed by zero
256  * that needed to be escaped with an extra backslash for doxygen) \\0
257  * as you want.
258  * This function is similar to DicomString(const char*), 
259  * except it doesn't take a lenght. 
260  * It only pad with a null character if length is odd
261  */
262 std::string Util::DicomString(const char* s)
263 {
264    size_t l = strlen(s);
265    if( l%2 )
266    {
267       l++;
268    }
269    std::string r(s, s+l);
270    assert( !(r.size() % 2) );
271    return r;
272 }
273
274 /**
275  * \ingroup Util
276  * \brief Safely compare two Dicom String:
277  *        - Both string should be of even lenght
278  *        - We allow padding of even lenght string by either a null 
279  *          character of a space
280  */
281 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
282 {
283   // s2 is the string from the DICOM reference: 'MONOCHROME1'
284   std::string s1_even = s1; //Never change input parameter
285   std::string s2_even = DicomString( s2 );
286   if( s1_even[s1_even.size()-1] == ' ')
287   {
288     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
289   }
290   return s1_even == s2_even;
291 }
292
293
294
295 /**
296  * \ingroup Util
297  * \brief   tells us if the processor we are working with is BigEndian or not
298  */
299 bool Util::IsCurrentProcessorBigEndian()
300 {
301    uint16_t intVal = 1;
302    uint8_t bigEndianRepr[4] = { 0x00, 0x00, 0x00, 0x01 };
303    int res = memcmp(reinterpret_cast<const void*>(&intVal),
304                     reinterpret_cast<const void*>(bigEndianRepr), 4);
305    if (res == 0)
306       return true;
307    else
308       return false;
309 }
310
311
312 #include <fcntl.h>
313 #include <stdlib.h>
314 #include <string.h>
315 #include <unistd.h>
316
317 #ifdef _WIN32
318 #include <snmp.h>
319 #include <conio.h>
320 #include <stdio.h>
321 typedef BOOL(WINAPI * pSnmpExtensionInit) (
322         IN DWORD dwTimeZeroReference,
323         OUT HANDLE * hPollForTrapEvent,
324         OUT AsnObjectIdentifier * supportedView);
325
326 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
327         OUT AsnObjectIdentifier * enterprise,
328         OUT AsnInteger * genericTrap,
329         OUT AsnInteger * specificTrap,
330         OUT AsnTimeticks * timeStamp,
331         OUT RFC1157VarBindList * variableBindings);
332
333 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
334         IN BYTE requestType,
335         IN OUT RFC1157VarBindList * variableBindings,
336         OUT AsnInteger * errorStatus,
337         OUT AsnInteger * errorIndex);
338
339 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
340         OUT AsnObjectIdentifier * supportedView);
341 #else
342 #include <strings.h> //for bzero on unix
343 #endif //_WIN32
344
345 #ifdef __linux__
346 #include <sys/ioctl.h>
347 #include <sys/types.h>
348 #include <sys/socket.h>
349 #include <netinet/in.h>
350 #include <linux/if.h>
351 #endif
352
353 #ifdef __HP_aCC
354 #include <netio.h>
355 #endif
356
357 #ifdef _AIX
358 #include <sys/ndd_var.h>
359 #include <sys/kinfo.h>
360 #endif
361
362 long GetMacAddrSys ( u_char *addr)
363 {
364 #ifdef _WIN32
365    WSADATA WinsockData;
366    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) {
367        fprintf(stderr, "This program requires Winsock 2.x!\n");
368        return;
369    }
370
371    HINSTANCE m_hInst;
372    pSnmpExtensionInit m_Init;
373    pSnmpExtensionInitEx m_InitEx;
374    pSnmpExtensionQuery m_Query;
375    pSnmpExtensionTrap m_Trap;
376    HANDLE PollForTrapEvent;
377    AsnObjectIdentifier SupportedView;
378    UINT OID_ifEntryType[] = {
379        1, 3, 6, 1, 2, 1, 2, 2, 1, 3
380    };
381    UINT OID_ifEntryNum[] = {
382        1, 3, 6, 1, 2, 1, 2, 1
383    };
384    UINT OID_ipMACEntAddr[] = {
385        1, 3, 6, 1, 2, 1, 2, 2, 1, 6
386    };                          //, 1 ,6 };
387    AsnObjectIdentifier MIB_ifMACEntAddr =
388        { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
389    AsnObjectIdentifier MIB_ifEntryType = {
390        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType
391    };
392    AsnObjectIdentifier MIB_ifEntryNum = {
393        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum
394    };
395    RFC1157VarBindList varBindList;
396    RFC1157VarBind varBind[2];
397    AsnInteger errorStatus;
398    AsnInteger errorIndex;
399    AsnObjectIdentifier MIB_NULL = {
400        0, 0
401    };
402    int ret;
403    int dtmp;
404    int i = 0, j = 0;
405    BOOL found = FALSE;
406    char TempEthernet[13];
407    m_Init = NULL;
408    m_InitEx = NULL;
409    m_Query = NULL;
410    m_Trap = NULL;
411
412    /* Load the SNMP dll and get the addresses of the functions
413       necessary */
414    m_hInst = LoadLibrary("inetmib1.dll");
415    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) {
416        m_hInst = NULL;
417        return;
418    }
419    m_Init =
420        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
421    m_InitEx =
422        (pSnmpExtensionInitEx) GetProcAddress(m_hInst,
423                                              "SnmpExtensionInitEx");
424    m_Query =
425        (pSnmpExtensionQuery) GetProcAddress(m_hInst,
426                                             "SnmpExtensionQuery");
427    m_Trap =
428        (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
429    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
430
431    /* Initialize the variable list to be retrieved by m_Query */
432    varBindList.list = varBind;
433    varBind[0].name = MIB_NULL;
434    varBind[1].name = MIB_NULL;
435
436    /* Copy in the OID to find the number of entries in the
437       Inteface table */
438    varBindList.len = 1;        /* Only retrieving one item */
439    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
440    ret =
441        m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
442                &errorIndex);
443 //   printf("# of adapters in this system : %i\n",
444 //          varBind[0].value.asnValue.number); varBindList.len = 2;
445
446    /* Copy in the OID of ifType, the type of interface */
447    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
448
449    /* Copy in the OID of ifPhysAddress, the address */
450    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
451
452    do {
453
454        /* Submit the query.  Responses will be loaded into varBindList.
455           We can expect this call to succeed a # of times corresponding
456           to the # of adapters reported to be in the system */
457        ret =
458            m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
459                    &errorIndex); if (!ret) ret = 1;
460
461        else
462            /* Confirm that the proper type has been returned */
463            ret =
464                SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
465                             MIB_ifEntryType.idLength); if (!ret) {
466            j++;
467            dtmp = varBind[0].value.asnValue.number;
468            //printf("Interface #%i type : %i\n", j, dtmp);
469
470            /* Type 6 describes ethernet interfaces */
471            if (dtmp == 6) {
472
473                /* Confirm that we have an address here */
474                ret =
475                    SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
476                                 MIB_ifMACEntAddr.idLength);
477                if ((!ret)
478                    && (varBind[1].value.asnValue.address.stream != NULL)) {
479                    if (
480                        (varBind[1].value.asnValue.address.stream[0] ==
481                         0x44)
482                        && (varBind[1].value.asnValue.address.stream[1] ==
483                            0x45)
484                        && (varBind[1].value.asnValue.address.stream[2] ==
485                            0x53)
486                        && (varBind[1].value.asnValue.address.stream[3] ==
487                            0x54)
488                        && (varBind[1].value.asnValue.address.stream[4] ==
489                            0x00)) {
490
491                        /* Ignore all dial-up networking adapters */
492                        //printf("Interface #%i is a DUN adapter\n", j);
493                        continue;
494                    }
495                    if (
496                        (varBind[1].value.asnValue.address.stream[0] ==
497                         0x00)
498                        && (varBind[1].value.asnValue.address.stream[1] ==
499                            0x00)
500                        && (varBind[1].value.asnValue.address.stream[2] ==
501                            0x00)
502                        && (varBind[1].value.asnValue.address.stream[3] ==
503                            0x00)
504                        && (varBind[1].value.asnValue.address.stream[4] ==
505                            0x00)
506                        && (varBind[1].value.asnValue.address.stream[5] ==
507                            0x00)) {
508
509                        /* Ignore NULL addresses returned by other network
510                           interfaces */
511                        //printf("Interface #%i is a NULL address\n", j);
512                        continue;
513                    }
514                    sprintf(addr, "%02x%02x%02x%02x%02x%02x",
515                            varBind[1].value.asnValue.address.stream[0],
516                            varBind[1].value.asnValue.address.stream[1],
517                            varBind[1].value.asnValue.address.stream[2],
518                            varBind[1].value.asnValue.address.stream[3],
519                            varBind[1].value.asnValue.address.stream[4],
520                            varBind[1].value.asnValue.address.stream[5]);
521                    //printf("MAC Address of interface #%i: %s\n", j, TempEthernet);
522               }
523            }
524        }
525    } while (!ret);         /* Stop only on an error.  An error will occur
526                               when we go exhaust the list of interfaces to
527                               be examined */
528    //getch();
529
530    /* Free the bindings */
531    SNMP_FreeVarBind(&varBind[0]);
532    SNMP_FreeVarBind(&varBind[1]);
533    return 0;
534 #endif //_WIN32
535
536 /* implementation for Linux */
537 #ifdef __linux__
538     struct ifreq ifr;
539     struct ifreq *IFR;
540     struct ifconf ifc;
541     char buf[1024];
542     int s, i;
543     int ok = 0;
544
545     s = socket(AF_INET, SOCK_DGRAM, 0);
546     if (s==-1) {
547         return -1;
548     }
549
550     ifc.ifc_len = sizeof(buf);
551     ifc.ifc_buf = buf;
552     ioctl(s, SIOCGIFCONF, &ifc);
553  
554     IFR = ifc.ifc_req;
555     for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
556
557         strcpy(ifr.ifr_name, IFR->ifr_name);
558         if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
559             if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
560                 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
561                     ok = 1;
562                     break;
563                 }
564             }
565         }
566     }
567
568     close(s);
569     if (ok) {
570         bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
571     }
572     else {
573         return -1;
574     }
575     return 0;
576 #endif
577
578 /* implementation for HP-UX */
579 #ifdef __HP_aCC
580
581 #define LAN_DEV0 "/dev/lan0"
582
583     int fd;
584     struct fis iocnt_block;
585     int i;
586     char net_buf[sizeof(LAN_DEV0)+1];
587     char *p;
588
589     (void)sprintf(net_buf, "%s", LAN_DEV0);
590     p = net_buf + strlen(net_buf) - 1;
591
592     /* 
593      * Get 802.3 address from card by opening the driver and interrogating it.
594      */
595     for (i = 0; i < 10; i++, (*p)++) {
596         if ((fd = open (net_buf, O_RDONLY)) != -1) {
597       iocnt_block.reqtype = LOCAL_ADDRESS;
598       ioctl (fd, NETSTAT, &iocnt_block);
599       close (fd);
600
601             if (iocnt_block.vtype == 6)
602                 break;
603         }
604     }
605
606     if (fd == -1 || iocnt_block.vtype != 6) {
607         return -1;
608     }
609
610   bcopy( &iocnt_block.value.s[0], addr, 6);
611   return 0;
612
613 #endif /* HPUX */
614
615 /* implementation for AIX */
616 #ifdef _AIX
617
618     int size;
619     struct kinfo_ndd *nddp;
620
621     size = getkerninfo(KINFO_NDD, 0, 0, 0);
622     if (size <= 0) {
623         return -1;
624     }
625     nddp = (struct kinfo_ndd *)malloc(size);
626           
627     if (!nddp) {
628         return -1;
629     }
630     if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
631         free(nddp);
632         return -1;
633     }
634     bcopy(nddp->ndd_addr, addr, 6);
635     free(nddp);
636     return 0;
637 #endif //_AIX
638
639 /* Not implemented platforms */
640   return -1;
641 }
642
643 std::string Util::GetMACAddress()
644 {
645    // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX 
646    // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
647    long stat;
648    u_char addr[6];
649    std::string macaddr;
650  
651    stat = GetMacAddrSys( addr);
652    if (0 == stat)
653    {
654       //printf( "MAC address = ");
655         for (int i=0; i<6; ++i) 
656         {
657             //printf("%2.2x", addr[i]);
658             macaddr += Format("%2.2x", addr[i]);
659         }
660        // printf( "\n");
661       return macaddr;
662    }
663    else
664    {
665       //printf( "No MAC address !\n" );
666       return "";
667    }
668 }
669
670 /**
671  * \ingroup Util
672  * \brief   Return the IP adress of the machine writting the DICOM image
673  */
674 std::string Util::GetIPAddress()
675 {
676   // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
677 #ifndef HOST_NAME_MAX
678   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
679   // POSIX 1003.1-2001 guarantees that `Host names (not including the
680   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
681 #  define HOST_NAME_MAX 255
682   // In this case we should maybe check the string was not truncated.
683   // But I don't known how to check that...
684 #if defined(_MSC_VER) || defined(__BORLANDC__)
685   // with WinSock DLL we need to initialise the WinSock before using gethostname
686   WORD wVersionRequested = MAKEWORD(1,0);
687   WSADATA WSAData;
688   int err = WSAStartup(wVersionRequested,&WSAData);
689   if (err != 0) {
690       /* Tell the user that we could not find a usable */
691       /* WinSock DLL.                                  */
692       WSACleanup();
693       return "127.0.0.1";
694   }
695 #endif
696   
697 #endif //HOST_NAME_MAX
698
699   std::string str;
700   char szHostName[HOST_NAME_MAX+1];
701   int r = gethostname(szHostName, HOST_NAME_MAX);
702
703   if( r == 0 )
704   {
705     // Get host adresses
706     struct hostent * pHost = gethostbyname(szHostName);
707
708     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
709     {
710       for( int j = 0; j<pHost->h_length; j++ )
711       {
712         if( j > 0 ) str += ".";
713
714         str += Util::Format("%u", 
715             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
716       }
717       // str now contains one local IP address 
718
719 #if defined(_MSC_VER) || defined(__BORLANDC__)
720   WSACleanup();
721 #endif
722   
723     }
724   }
725   // If an error occur r == -1
726   // Most of the time it will return 127.0.0.1...
727   return str;
728 }
729
730 /**
731  * \ingroup Util
732  * \brief Creates a new UID. As stipulate in the DICOM ref
733  *        each time a DICOM image is create it should have 
734  *        a unique identifier (URI)
735  */
736 std::string Util::CreateUniqueUID(const std::string& root)
737 {
738   // The code works as follow:
739   // echo "gdcm" | od -b
740   // 0000000 147 144 143 155 012
741   // Therefore we return
742   // radical + 147.144.143.155 + IP + time()
743   std::string radical = root;
744   if( !root.size() ) //anything better ?
745   {
746     radical = "0.0."; // Is this really usefull ?
747   }
748   // else
749   // A root was specified use it to forge our new UID:
750   radical += "147.144.143.155"; // gdcm
751   radical += ".";
752   radical += Util::GetIPAddress();
753   radical += ".";
754   radical += Util::GetCurrentDate();
755   radical += ".";
756   radical += Util::GetCurrentTime();
757
758   return radical;
759 }
760
761 template <class T>
762 std::ostream& binary_write(std::ostream& os, const T& val)
763 {
764     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
765 }
766
767 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
768 {
769 #ifdef GDCM_WORDS_BIGENDIAN
770     uint16_t swap;
771     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
772     return os.write(reinterpret_cast<const char*>(&swap), 2);
773 #else
774     return os.write(reinterpret_cast<const char*>(&val), 2);
775 #endif //GDCM_WORDS_BIGENDIAN
776 }
777
778 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
779 {
780 #ifdef GDCM_WORDS_BIGENDIAN
781     uint32_t swap;
782     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
783              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
784     return os.write(reinterpret_cast<const char*>(&swap), 4);
785 #else
786     return os.write(reinterpret_cast<const char*>(&val), 4);
787 #endif //GDCM_WORDS_BIGENDIAN
788 }
789
790 std::ostream& binary_write(std::ostream& os, const char* val)
791 {
792     return os.write(val, strlen(val));
793 }
794
795 std::ostream& binary_write(std::ostream& os, std::string const & val)
796 {
797     return os.write(val.c_str(), val.size());
798 }
799
800 } // end namespace gdcm
801