1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2009/02/05 09:50:09 $
7 Version: $Revision: 1.55 $
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.
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.
17 =========================================================================*/
19 #include "gdcmDataEntry.h"
22 #include "gdcmGlobal.h"
24 #include "gdcmDebug.h"
28 #if defined(__BORLANDC__)
29 #include <mem.h> // for memcpy
30 #include <stdlib.h> // for atof
31 #include <ctype.h> // for isdigit
33 #include <string.h> // memcpy
34 #include <stdlib.h> // atof
36 // Could be defined like MAX_SIZE_LOAD_ELEMENT_VALUE
37 #define GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA 8
39 namespace GDCM_NAME_SPACE
41 //-----------------------------------------------------------------------------
42 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
43 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
45 //-----------------------------------------------------------------------------
46 // Constructor / Destructor
48 * \brief Constructor for a given DataEntry
49 * @param group group number of the Data Entry to be created
50 * @param elem element number of the Data Entry to be created
51 * @param vr Value Representation of the Data Entry to be created
53 DataEntry::DataEntry(uint16_t group,uint16_t elem,
55 : DocEntry(group,elem,vr)
67 * \brief Constructor for a given DocEntry
68 * @param e Pointer to existing Doc entry
70 DataEntry::DataEntry(DocEntry *e)
71 //: DocEntry(e->GetDictEntry())
72 : DocEntry(e->GetGroup(),e->GetElement(), e->GetVR() )
83 * \brief Canonical destructor.
85 DataEntry::~DataEntry ()
91 //-----------------------------------------------------------------------------
94 * \brief Sets the value (non string) of the current DataEntry
96 * @param self self=true : The area : *belongs" to the DataEntry
97 * : will be delete with the DataEntry
98 * self=false The area *is not* deleted with the DataEntry
101 void DataEntry::SetBinArea( uint8_t *area, bool self )
108 State = STATE_LOADED;
111 * \brief Inserts the value (non string) into the current DataEntry
113 * @param length length
115 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
119 uint32_t lgh = length + length%2;
122 if( area && length > 0 )
125 memcpy(BinArea,area,length);
127 BinArea[length]=0; // padd with zero
129 State = STATE_LOADED;
134 * \brief Checks wether the current DataEntry contains number(s)
137 bool DataEntry::IsNumerical()
139 const VRKey &vr = GetVR();
155 * \brief Gets a std::vector of 'double' holding the value(s) of any 'numerical' DataEntry
156 * @param valueVector std::vector double of value(s)
157 * \return false if VR not "a 'numerical" one
159 bool DataEntry::GetNumerical(std::vector <double> &valueVector)
163 if (!IsNumerical()) // never trust a user !
166 const VRKey &vr = GetVR();
168 if (vr == "IS" || vr == "DS")
170 /// \todo rewrite the whole method, in order *not to use* std::string !
171 std::vector<std::string> tokens;
173 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
175 int nbValues= tokens.size();
180 for (loop=0; loop<nbValues; loop++)
181 valueVector.push_back(atof(tokens[loop].c_str()));
183 for (loop=0; loop<nbValues; loop++)
184 valueVector.push_back(atoi(tokens[loop].c_str()));
189 uint32_t nbValues = GetValueCount();
194 for (loop=0; loop<nbValues; loop++)
195 valueVector.push_back(((uint16_t *)BinArea)[loop]);
199 for (loop=0; loop<nbValues; loop++)
200 valueVector.push_back(((int16_t *)BinArea)[loop]);
204 for (loop=0; loop<nbValues; loop++)
205 valueVector.push_back(((uint32_t *)BinArea)[loop]);
209 for (loop=0; loop<nbValues; loop++)
210 valueVector.push_back(((int32_t *)BinArea)[loop]);
214 for (loop=0; loop<nbValues; loop++)
215 valueVector.push_back(((float *)BinArea)[loop]);
219 for (loop=0; loop<nbValues; loop++)
220 valueVector.push_back(((double *)BinArea)[loop]);
227 * \brief Inserts the elementary (non string) value into the current DataEntry
228 * @param id index of the elementary value to be set
229 * @param val value, passed as a double
231 void DataEntry::SetValue(const uint32_t &id, const double &val)
235 State = STATE_LOADED;
237 if( id > GetValueCount() )
239 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
243 const VRKey &vr = GetVR();
244 if( vr == "US" || vr == "SS" )
246 uint16_t *data = (uint16_t *)BinArea;
247 data[id] = (uint16_t)val;
249 else if( vr == "UL" || vr == "SL" )
251 uint32_t *data = (uint32_t *)BinArea;
252 data[id] = (uint32_t)val;
254 else if( vr == "FL" )
256 float *data = (float *)BinArea;
257 data[id] = (float)val;
259 else if( vr == "FD" )
261 double *data = (double *)BinArea;
262 data[id] = (double)val;
264 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
266 gdcmErrorMacro("SetValue on String representable not implemented yet");
270 BinArea[id] = (uint8_t)val;
274 * \brief returns, as a double one of the values
275 * (when entry is multivaluated), identified by its index.
276 * Returns 0.0 if index is wrong
279 double DataEntry::GetValue(const uint32_t &id) const
283 if (GetLength() != 0) // avoid stupid messages
284 /// \todo warn the user there was a problem !
285 gdcmErrorMacro("BinArea not set " << std::hex
286 << GetGroup() << " " << GetElement()
287 << " Can't get the value");
291 uint32_t count = GetValueCount();
294 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
298 // if user *knows* that entry contains a US,
299 // he just has to cast the double he receives
301 const VRKey &vr = GetVR();
303 if( vr == "US" || vr == "SS" )
304 return ((uint16_t *)BinArea)[id];
305 else if( vr == "UL" || vr == "SL" )
306 return ((uint32_t *)BinArea)[id];
307 else if( vr == "FL" )
308 return ((float *)BinArea)[id];
309 else if( vr == "FD" )
310 return ((double *)BinArea)[id];
311 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
313 // this is for VR = "DS", ...
316 // Don't use std::string to accelerate processing
318 char *tmp = new char[GetLength()+1];
319 memcpy(tmp,BinArea,GetLength());
330 for(uint32_t i=0;i<GetLength();i++)
360 * \brief Checks if the multiplicity of the value follows Dictionary VM
362 bool DataEntry::IsValueCountValid() /*const*/
365 const std::string &strVM = GetVM();
366 uint32_t vc = GetValueCount();
367 bool valid = vc == 0;
371 // FIXME : what shall we do with VM = "2-n", "3-n", etc
375 // make sure there is at least one ??? FIXME
380 std::istringstream os;
384 // vm respects the one from the dict
385 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
389 // Entries whose type is 1 are mandatory, with a mandatory value.
390 // Entries whose type is 1c are mandatory-inside-a-Sequence,
391 // with a mandatory value.
392 // Entries whose type is 2 are mandatory, with an optional value.
393 // Entries whose type is 2c are mandatory-inside-a-Sequence,
394 // with an optional value.
395 // Entries whose type is 3 are optional.
397 // case vc == 0 is only applicable for 'type 2' entries.
398 // Problem : entry type may depend on the modality and/or the Sequence
399 // it's embedded in !
400 // (Get the information in the 'Conformance Statements' ...)
407 * \brief returns the number of elementary values
409 uint32_t DataEntry::GetValueCount( ) const
411 const VRKey &vr = GetVR();
412 if( vr == "US" || vr == "SS" )
413 return GetLength()/sizeof(uint16_t);
414 else if( vr == "UL" || vr == "SL" )
415 return GetLength()/sizeof(uint32_t);
416 else if( vr == "FL" || vr == "OF" )
417 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
418 else if( vr == "FD" )
419 return GetLength()/8; // FD has a *8* length! sizeof(double);
420 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
422 // Some element in DICOM are allowed to be empty
425 // Don't use std::string to accelerate processing
427 for(uint32_t i=0;i<GetLength();i++)
429 if( BinArea[i] == '\\')
438 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
439 * @param valueVector std::vector double of value(s)
440 * \return false if VR not "DS" or DataEntry empty
442 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
444 /// \todo rewrite the whole method, in order *not to use* std::string !
445 std::vector<std::string> tokens;
447 if (GetVR() != "DS") // never trust a user !
450 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
452 int nbValues= tokens.size();
456 for (int loop=0; loop<nbValues; loop++)
457 valueVector.push_back(atof(tokens[loop].c_str()));
463 * \brief Sets the 'value' of a DataEntry, passed as a std::string
464 * @param value string representation of the value to be set
466 void DataEntry::SetString(std::string const &value)
469 const VRKey &vr = GetVR();
470 if ( vr == "US" || vr == "SS" )
472 std::vector<std::string> tokens;
473 Util::Tokenize (value, tokens, "\\");
474 SetLength(tokens.size()*sizeof(uint16_t));
477 uint16_t *data = (uint16_t *)BinArea;
478 for (unsigned int i=0; i<tokens.size();i++)
479 data[i] = atoi(tokens[i].c_str());
482 else if ( vr == "UL" || vr == "SL" )
484 std::vector<std::string> tokens;
485 Util::Tokenize (value, tokens, "\\");
486 SetLength(tokens.size()*sizeof(uint32_t));
489 uint32_t *data = (uint32_t *)BinArea;
490 for (unsigned int i=0; i<tokens.size();i++)
491 data[i] = atoi(tokens[i].c_str());
494 else if ( vr == "FL" )
496 std::vector<std::string> tokens;
497 Util::Tokenize (value, tokens, "\\");
498 SetLength(tokens.size()*sizeof(float));
501 float *data = (float *)BinArea;
502 for (unsigned int i=0; i<tokens.size();i++)
503 data[i] = (float)atof(tokens[i].c_str());
506 else if ( vr == "FD" )
508 std::vector<std::string> tokens;
509 Util::Tokenize (value, tokens, "\\");
510 SetLength(tokens.size()*sizeof(double));
513 double *data = (double *)BinArea;
514 for (unsigned int i=0; i<tokens.size();i++)
515 data[i] = atof(tokens[i].c_str());
520 size_t l = value.size();
523 memcpy(BinArea, value.c_str(), l);
524 if (l%2) // padded with blank except for UI
532 State = STATE_LOADED;
535 * \brief returns as a string (when possible) the value of the DataEntry
537 std::string const &DataEntry::GetString() const
539 static std::ostringstream s;
540 const VRKey &vr = GetVR();
544 StrArea = new std::string();
550 // When short integer(s) are stored, convert the following (n * 2) characters
551 // as a displayable string, the values being separated by a back-slash
554 uint16_t *data=(uint16_t *)BinArea;
555 for (unsigned int i=0; i < GetValueCount(); i++)
563 else if (vr == "SS" )
565 int16_t *data=(int16_t *)BinArea;
566 for (unsigned int i=0; i < GetValueCount(); i++)
573 } // See above comment on multiple short integers (mutatis mutandis).
574 else if( vr == "UL" )
576 uint32_t *data=(uint32_t *)BinArea;
577 for (unsigned int i=0; i < GetValueCount(); i++)
585 else if( vr == "SL" )
587 int32_t *data=(int32_t *)BinArea;
588 for (unsigned int i=0; i < GetValueCount(); i++)
595 } // See above comment on multiple short integers (mutatis mutandis).
596 else if( vr == "FL" )
598 float *data=(float *)BinArea;
599 for (unsigned int i=0; i < GetValueCount(); i++)
606 } // See above comment on multiple short integers (mutatis mutandis).
607 else if( vr == "FD" )
609 double *data=(double *)BinArea;
610 for (unsigned int i=0; i < GetValueCount(); i++)
620 StrArea->append((const char *)BinArea,GetLength());
621 // to avoid gdcm to propagate oddities in lengthes
623 StrArea->append(" ",1);
629 * \brief returns an hexadecimal representation of the DataEntry value
631 std::string const &DataEntry::GetHexaRepresentation() const
633 static std::ostringstream s2;
634 const VRKey &vr = GetVR();
638 StrHexaArea = new std::string();
643 // When short integer(s) are stored, convert the following (n * 2) characters
644 // as a displayable string, the values being separated by a back-slash
650 uint16_t *data=(uint16_t *)BinArea;
651 for (unsigned int i=0; i < GetValueCount(); i++)
653 s2 << std::setw( 2 ) << std::setfill( '0' );
658 *StrHexaArea=s2.str();
660 else if (vr == "SS" )
662 int16_t *data=(int16_t *)BinArea;
663 for (unsigned int i=0; i < GetValueCount(); i++)
665 s2 << std::setw( 4 ) << std::setfill( '0' );
670 *StrHexaArea=s2.str();
671 } // See above comment on multiple short integers (mutatis mutandis).
672 else if( vr == "UL" )
674 uint32_t *data=(uint32_t *)BinArea;
675 for (unsigned int i=0; i < GetValueCount(); i++)
677 s2 << std::setw( 4 ) << std::setfill( '0' );
682 *StrHexaArea=s2.str();
684 else if( vr == "SL" )
686 int32_t *data=(int32_t *)BinArea;
687 for (unsigned int i=0; i < GetValueCount(); i++)
689 s2 << std::setw( 4 ) << std::setfill( '0' );
694 *StrHexaArea=s2.str();
696 else if( vr == "FL" )
698 unsigned char *toto=(unsigned char *)BinArea;
699 for (unsigned int i=0; i < GetValueCount(); i++)
705 for(int iif=0; iif<4; iif++)
711 *StrHexaArea=s2.str();
713 else if( vr == "FD" )
715 //double *data=(double *)BinArea;
716 unsigned char *toto=(unsigned char *)BinArea;
717 for (unsigned int i=0; i < GetValueCount(); i++)
725 for(int iid=0; iid<8; iid++)
732 *StrHexaArea=s2.str();
736 unsigned int l = (Length > GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA) ? GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA : Length;
737 uint8_t *data=(uint8_t *)BinArea;
738 for (unsigned int i=0; i < l; i++)
742 s2 << std::setw( 2 ) << (int)(data[i]);
746 *StrHexaArea=s2.str();
752 * \brief Copies all the attributes from an other DocEntry
753 * @param doc entry to copy from
754 * @remarks The content BinArea is copied too (StrArea is not)
756 void DataEntry::Copy(DocEntry *doc)
760 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
763 State = entry->State;
765 CopyBinArea(entry->BinArea,entry->GetLength());
770 * \brief Writes the 'common part' + the 'value' area of a DataEntry
771 * @param fp already open ofstream pointer
772 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
774 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
775 bool insideMetaElements, bool insideSequence)
777 // writes the 'common part'
778 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
780 if ( GetGroup() == 0xfffe )
782 return; //delimitors have NO value
785 // --> We only deal with Little Endian writting.
786 // --> forget Big Endian Transfer Syntax writting!
787 // Next DICOM version will give it up ...
789 // WARNING - For Implicit VR private element,
790 // we have *no choice* but considering them as
791 // something like 'OB' values.
792 // we rewrite them as we found them on disc.
793 // Some trouble will occur if element was
794 // *actually* OW, if image was produced
795 // on Big endian based processor, read and writen
796 // on Little endian based processor
797 // and, later on, somebody needs
798 // this 'OW' Implicit VR private element (?!?)
799 // (Same stuff, mutatis mutandis, for Little/Big)
801 // 8/16 bits Pixels problem should be solved automatiquely,
802 // since we ensure the VR (OB vs OW) is conform to Pixel size.
804 uint8_t *data = BinArea; //safe notation
805 size_t l = GetLength();
806 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
807 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
809 if (BinArea) // the binArea was *actually* loaded
811 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
812 unsigned short vrLgth =
813 Global::GetVR()->GetAtomicElementLength(this->GetVR());
819 binary_write (*fp, data, l );
824 uint16_t *data16 = (uint16_t *)data;
825 for(i=0;i<l/vrLgth;i++)
826 binary_write( *fp, data16[i]);
831 uint32_t *data32 = (uint32_t *)data;
832 for(i=0;i<l/vrLgth;i++)
833 binary_write( *fp, data32[i]);
838 double *data64 = (double *)data;
839 for(i=0;i<l/vrLgth;i++)
840 binary_write( *fp, data64[i]);
845 binary_write (*fp, data, l );
846 #endif //GDCM_WORDS_BIGENDIAN
851 // nothing was loaded, but we need to skip space on disc
854 // --> WARNING : nothing is written;
855 // --> the initial data (on the the source image) is lost
856 // --> user is *not* informed !
857 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
858 << "Length =" << l << " for " << GetKey() );
859 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
862 // to avoid gdcm to propagate oddities
863 // (length was already modified)
865 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
869 * \brief Compute the full length of the elementary DataEntry (not only value
870 * length) depending on the VR.
872 uint32_t DataEntry::ComputeFullLength()
874 return GetFullLength();
877 //-----------------------------------------------------------------------------
880 /// \brief Creates a DataEntry owned BinArea
881 /// (remove previous one if any and relevant StrArea if any)
882 void DataEntry::NewBinArea( )
885 if( GetLength() > 0 )
886 BinArea = new uint8_t[GetLength()];
889 /// \brief Removes the BinArea, if owned by the DataEntry,
890 /// and the relevant StrArea if any
891 void DataEntry::DeleteBinArea(void)
893 if (BinArea && SelfArea)
910 //-----------------------------------------------------------------------------
913 //-----------------------------------------------------------------------------
916 * \brief Prints a DataEntry (Dicom entry)
917 * @param os ostream we want to print in
918 * @param indent Indentation string to be prepended during printing
920 void DataEntry::Print(std::ostream &os, std::string const & )
924 // First, Print the common part (vr [length offset] name).
927 uint16_t g = GetGroup();
928 if (g == 0xfffe) // delimiters have NO value
930 return; // just to avoid identing all the remaining code
933 std::ostringstream s;
939 const VRKey &vr = GetVR();
941 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
942 || vr == "FL" || vr == "FD")
943 s << " [" << GetString() << "] =0x(" << GetHexaRepresentation() << ")";
946 if(Global::GetVR()->IsVROfStringRepresentable(vr))
948 // replace non printable characters by '.'
949 std::string cleanString = Util::CreateCleanString(v);
950 if ( cleanString.length() <= GetMaxSizePrintEntry()
953 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
954 // FIXME : PrintLevel<2 *does* print the values
955 // (3 is only for extra offsets printing)
956 // What do you wanted to do ? JPR
958 s << " [" << cleanString << "]";
962 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
967 // A lot of Private elements (with no VR) contain actually
968 // only printable characters;
969 // Let's deal with them as is they were VR std::string representable
971 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
973 // FIXME : since the 'Area' *is* clean, just use
974 // a 'CreateString' method, to save CPU time.
975 std::string cleanString =
976 Util::CreateCleanString( BinArea,GetLength() );
977 s << " [" << cleanString << "]";
981 s << " [" << GDCM_BINLOADED << ";"
982 << "length = " << GetLength() << "] =0x(" << GetHexaRepresentation() << ")";
990 s << " [" << GDCM_NOTLOADED << "]";
991 else if( IsUnfound() )
992 s << " [" << GDCM_UNFOUND << "]";
993 else if( IsUnread() )
994 s << " [" << GDCM_UNREAD << "]";
995 else if ( GetLength() == 0 )
1000 s << " (" << GDCM_PIXELDATA << ")";
1002 // Display the UID value (instead of displaying only the rough code)
1003 // First 'clean' trailing character (space or zero)
1006 const uint16_t &gr = GetGroup();
1007 const uint16_t &elt = GetElement();
1008 TS *ts = Global::GetTS();
1012 // Any more to be displayed ?
1013 if ( elt == 0x0010 || elt == 0x0002 )
1015 if ( v.length() != 0 ) // for brain damaged headers
1017 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1019 v.erase(v.length()-1, 1);
1022 s << " ==>\t[" << ts->GetValue(v) << "]";
1025 else if (gr == 0x0008)
1027 if ( elt == 0x0016 || elt == 0x1150 )
1029 if ( v.length() != 0 ) // for brain damaged headers
1031 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1033 v.erase(v.length()-1, 1);
1036 s << " ==>\t[" << ts->GetValue(v) << "]";
1039 else if (gr == 0x0004)
1041 if ( elt == 0x1510 || elt == 0x1512 )
1043 if ( v.length() != 0 ) // for brain damaged headers
1045 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1047 v.erase(v.length()-1, 1);
1050 s << " ==>\t[" << ts->GetValue(v) << "]";
1058 //-----------------------------------------------------------------------------
1059 } // end namespace gdcm