Skip to Content
go-dicom(3)

Character sets

How go-dicom reads text in the character set a file declares, hands it to you as UTF-8, and writes it back, and what the charset package offers when you need the bytes in another set. It is for anyone whose files hold names or descriptions outside plain ASCII.

Overview

DICOM text is bytes, and Specific Character Set (0008,0005) says how to read them (PS3.3 C.12.1.1.2, PS3.5 6.1). With no declaration, the text must be ASCII. A declaration names one term, such as ISO_IR 100 for Latin-1 or ISO_IR 192 for UTF-8, or several, for text that switches sets with ISO 2022 escape sequences, as Japanese and Korean files do.

go-dicom decodes when it builds the data set, not when you ask for a value:

  • What you read is UTF-8. GetStringByKeyword, GetPersonName and the other accessors return Go strings, whatever the file declared.
  • The data set says so. Its Specific Character Set reads ISO_IR 192 once its text is UTF-8, so writing it back gives the next reader a file that describes itself correctly.
  • The original is kept. DICOMFile.DataElements holds the bytes as stored, and DICOMFile.DeclaredCharacterSet() the declaration the file made.

Supported character sets

charset.GetSupportedEncodings() lists the 32 terms this build knows:

TermsEncodingFor
none, ISO_IR 6, ISO 2022 IR 6ASCIIThe default repertoire
ISO_IR 100, 101, 109, 110, 148ISO-8859-1, -2, -3, -4, -9Latin alphabets: Western, Central, South and North European, Turkish
ISO_IR 126, 127, 138, 144, 166ISO-8859-7, -6, -8, -5, -11Greek, Arabic, Hebrew, Cyrillic, Thai
ISO 2022 IR 100 … ISO 2022 IR 166as aboveThe same sets, with code extensions
ISO_IR 13, ISO 2022 IR 13JIS X 0201Japanese Romaji and half-width Katakana
ISO 2022 IR 87, ISO 2022 IR 159JIS X 0208, JIS X 0212Japanese Kanji, by ISO 2022 escape
ISO 2022 IR 149KS X 1001Korean, by ISO 2022 escape
ISO 2022 IR 58GB 2312Simplified Chinese, by ISO 2022 escape
ISO_IR 192UTF-8Unicode
GB18030, GBKGB 18030, GBKChinese, without escapes

charset.GetEncodingInfo(term) gives a term's encoding, description and escape sequence. Measured against pydicom's seventeen character set files (Arabic, Greek, Hebrew, Japanese, Korean, Russian, Chinese and accented Latin), every patient name reads as pydicom reads it (CONFORMANCE.md §6).

Read text

Nothing is needed beyond an ordinary read:

func printName(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
	df, err := filereader.ReadDICOMFile(filebase.NewFileReader(f))
	if err != nil {
		return err
	}
	ds := df.GetDataset()

	fmt.Printf("declared %q, now %q\n", df.DeclaredCharacterSet(), ds.GetStringByKeyword("SpecificCharacterSet"))
	fmt.Println(ds.GetStringByKeyword("PatientName"))

	pn, err := ds.GetPersonName(ds.KeywordToTag("PatientName"))
	if err != nil {
		return err
	}
	fmt.Printf("alphabetic %q, ideographic %q, phonetic %q\n", pn.Alphabetic, pn.Ideographic, pn.Phonetic)
	for _, w := range df.Warnings {
		fmt.Println("warning:", w)
	}
	return nil
}

On pydicom's chrH31.dcm, which declares \ISO 2022 IR 87, and chrRuss.dcm, which declares ISO_IR 144:

declared ["" "ISO 2022 IR 87"], now "ISO_IR 192"
Yamada^Tarou=山田^太郎=やまだ^たろう
alphabetic "Yamada^Tarou", ideographic "山田^太郎", phonetic "やまだ^たろう"

declared ["ISO_IR 144"], now "ISO_IR 192"
Люкceмбypг
alphabetic "Люкceмбypг", ideographic "", phonetic ""

A person name has up to three component groups separated by =: alphabetic, ideographic and phonetic (PS3.5 6.2.1). GetPersonName splits them, and FamilyName(), GivenName() and the other methods split a group into its ^ components. DeclaredCharacterSet() returns the terms in order, with an empty first term where the file left the default repertoire unnamed, and nil when the file declares nothing.

Undeclared and unknown character sets

A file that declares nothing, declares an empty value, or names a term this build does not know is decoded as ISO-8859-1. Where that matters, because some text is outside ASCII, the read says so:

warning: text with no usable Specific Character Set (0008,0005) was decoded as ISO-8859-1, which is a guess; the default repertoire is ASCII (PS3.5 6.1.2.3)

The data set then declares ISO_IR 192, and gains the declaration if the file had none. Older equipment often writes Latin-1 without declaring it, and pydicom reads such files the same way.

Warning

A byte sequence that is not valid in the declared set is decoded to U+FFFD (�), with no warning. A file that declares ISO_IR 192 but holds Latin-1 bytes reads as Buc^J�r�me, and writing that data set back loses the original characters. Keep the source file, or the stored bytes in DataElements, if you may need them.

Items with their own character set

A sequence item may declare its own Specific Character Set, which applies to that item and the items below it. Each item is decoded with the declaration in force for it, and an item that declared one then declares ISO_IR 192 too. pydicom's chrSQEncoding.dcm declares UTF-8 at the top and ISO 2022 IR 13\ISO 2022 IR 87 in an item; the item's Patient's Name reads ヤマダ^タロウ=山田^太郎=やまだ^たろう.

The bytes as stored

For a UN value, which the data set does not decode (a private element in an Implicit VR file whose VR is not in the dictionary is one), or to see what the file really holds, decode the stored bytes with the file's own declaration:

encodings, err := charset.ConvertEncodings(df.DeclaredCharacterSet())
if err != nil {
	return err
}
for _, e := range df.DataElements {
	if e.Tag == tag.New(0x0010, 0x0010) {
		text, err := charset.DecodeBytes(e.Value, encodings, charset.PersonNameDelimiters)
		if err != nil {
			return err
		}
		fmt.Printf("%q\n%s\n", e.Value, text)
	}
}

On chrH31.dcm:

"Yamada^Tarou=\x1b$B;3ED\x1b(B^\x1b$BB@O:\x1b(B=\x1b$B$d$^$@\x1b(B^\x1b$B$?$m$&\x1b(B"
Yamada^Tarou=山田^太郎=やまだ^たろう

ConvertEncodings turns DICOM terms into the encoding names the rest of the package takes (ISO_IR 144 becomes ISO-8859-5, ISO 2022 IR 87 ISO-2022-JP, an empty or unknown term ISO-8859-1). The delimiters are the characters that end an escape run: PersonNameDelimiters adds ^ and = to the DefaultTextDelimiters (LF, CR, TAB, FF). For a single element in a streamed read, the filereader/attributes package has TextEncodings and DecodeText, which take the same decisions as GetDataset.

Write text

A data set holds UTF-8, so filewriter writes UTF-8, and the Specific Character Set the data set carries says ISO_IR 192. Set a value as a Go string:

if err := ds.SetStringByKeyword("PatientName", "Müller^Jörg"); err != nil {
	return err
}
if !ds.ContainsByKeyword("SpecificCharacterSet") {
	// Text outside ASCII needs a declaration, and nothing adds one for you.
	if err := ds.AddByKeyword("SpecificCharacterSet", dataelem.CS, "ISO_IR 192"); err != nil {
		return err
	}
}

Important

A data set read from a file that had only ASCII text, and declared nothing, still declares nothing. Setting a non-ASCII value does not add a declaration, and the file written then holds UTF-8 that a reader takes as ASCII. Add SpecificCharacterSet ISO_IR 192 as above whenever you write text outside ASCII.

The writer does not convert text to another character set on its way out. To store a value in Latin-1, Cyrillic or another set, encode it yourself and declare that set; the next section shows how.

Encode in another character set

charset.EncodeString encodes a Go string under a list of encodings as ConvertEncodings returns them, and DecodeBytes reverses it. Encode strictly, so that a character the set cannot hold is an error:

encodings, err := charset.ConvertEncodings([]string{"ISO_IR 100"})
if err != nil {
	return err
}
ctx := config.StrictWriting(context.Background())

b, err := charset.EncodeStringWithContext(ctx, "Buc^Jérôme", encodings)
fmt.Printf("%q %v\n", b, err)

_, err = charset.EncodeStringWithContext(ctx, "山田", encodings)
fmt.Println(err != nil, err)

It prints:

"Buc^J\xe9r\xf4me" <nil>
true encoding: rune not supported by encoding.

Caution

Without config.StrictWriting, a character the set cannot hold is not an error: EncodeString, EncodeToBytes, EncodeElement, BatchEncodeStrings and the writer in filewriter.NewDICOMFileWriterWithCharset log a warning and return the value's UTF-8 bytes with a nil error. Declared as ISO_IR 100, those bytes are wrong for every reader. The same happens when the encodings are DICOM terms such as ISO_IR 100 rather than what ConvertEncodings returns. Pass a strict context, or config.Get().SetWritingValidationMode(config.RAISE), and use ConvertEncodings first.

charset.NewCharacterSet(terms) holds a declaration with its encodings (Encodings, PrimaryEncoding(), SupportsCodeExtensions()), for EncodeWithCharset and DecodeWithCharset. It does not refuse an unknown term: it falls back to ISO-8859-1 with a warning. charset.ValidateEncoding does refuse one (unknown or unsupported encoding: ISO_IR 999).

ISO 2022 escape sequences

With several terms, the first is the set a value starts in, and the others are switched to by escape sequences in the bytes (PS3.5 6.1.2.5). Each run returns to the first set at the end of the value, and before each delimiter.

encodings, err := charset.ConvertEncodings([]string{"", "ISO 2022 IR 87"})
if err != nil {
	return err
}
b, err := charset.EncodeString("Yamada^Tarou=山田^太郎", encodings)
if err != nil {
	return err
}
fmt.Printf("%q\n", b)
for _, e := range charset.FindEscapeSequences(b) {
	fmt.Printf("at %d: %q selects %s\n", e.Position, e.Sequence, e.Encoding)
}

It prints:

"Yamada^Tarou=\x1b$B;3ED\x1b(B^\x1b$BB@O:\x1b(B"
at 13: "\x1b$B" selects ISO-2022-JP
at 20: "\x1b(B" selects ISO-8859-1
at 24: "\x1b$B" selects ISO-2022-JP
at 31: "\x1b(B" selects ISO-8859-1

SplitByEscapeSequences cuts a value into its runs, each beginning with the escape that selected it, and StripEscapeSequence takes the escape off the front of one. charset.ESC is the escape byte, 0x1B.

Cut a value where a character ends

To store or show a long value in pieces, such as text cut to a column width, each piece must decode alone to its part of the text. A cut in the middle of a multi-byte character, or one that drops the escape in force, breaks that. charset.CharacterLength(encoding, escape, b) gives the length of the character b begins with, as the decoder reads it:

// splitText cuts value into pieces of at most max bytes, each of which decodes
// alone. A piece inside an ISO 2022 run begins with the escape in force.
func splitText(value []byte, encoding string, max int) [][]byte {
	var pieces [][]byte
	var piece, escape []byte
	for i := 0; i < len(value); {
		n := charset.CharacterLength(encoding, escape, value[i:])
		if n <= 0 { // the value ends inside a character, or the encoding is unknown
			n = len(value) - i
		}
		isEscape := value[i] == charset.ESC
		if len(piece) > 0 && len(piece)+n > max {
			pieces = append(pieces, piece)
			piece = nil
			if !isEscape {
				piece = append(piece, escape...)
			}
		}
		switch {
		case isEscape:
			escape = value[i : i+n]
		case value[i] == '\n':
			escape = nil // LF returns the run to the first set
		}
		piece = append(piece, value[i:i+n]...)
		i += n
	}
	if len(piece) > 0 {
		pieces = append(pieces, piece)
	}
	return pieces
}

Cut to five bytes, the ISO 2022 value above becomes pieces that each decode alone, and decoded and joined they give the whole:

"Yamad" "a^Tar" "ou=" "\x1b$B;3" "\x1b$BED" "\x1b(B^" "\x1b$BB@" "\x1b$BO:" "\x1b(B"
Yamada^Tarou=山田^太郎

CharacterLength returns -1 when b ends inside the character, and 0 when b is empty or the encoding is unknown, or is GB 2312, whose shifts are not set by an escape. Only the JIS X 0208 and JIS X 0212 escapes (ESC $ B, ESC $ @, ESC $ ( D) change the answer; pass nil as escape in the first set.

On the command line

go-dicom show prints text decoded, and the Specific Character Set as the file stores it:

$ go-dicom show chrH31.dcm::SpecificCharacterSet
0008,0005    CS  16      \ISO 2022 IR 87 
$ go-dicom show chrH31.dcm::PatientName
0010,0010    PN  60      Yamada^Tarou=山田^太郎=やまだ^たろう
$ go-dicom show chrRuss.dcm::PatientName
0010,0010    PN  10      Люкceмбypг

go-dicom modify writes what it changes as UTF-8, and checks the declaration before it writes anything:

$ go-dicom modify -set PatientName='Müller^Jörg' mr.dcm mr2.dcm
Error: modify: -set PatientName=Müller^Jörg: (0010,0010) PN: "Müller^Jörg" is not ASCII and the file declares no Specific Character Set; insert SpecificCharacterSet='ISO_IR 192' before it in the same command
$ go-dicom modify -insert SpecificCharacterSet='ISO_IR 192' -set PatientName='Müller^Jörg' mr.dcm mr2.dcm
Wrote mr2.dcm: 2 change(s), transfer syntax 1.2.840.10008.1.2.1
$ go-dicom modify -set PatientName='Müller^Jörg' chrRuss.dcm russ2.dcm
Wrote russ2.dcm: 1 change(s), transfer syntax 1.2.840.10008.1.2.1
$ go-dicom show russ2.dcm::SpecificCharacterSet
0008,0005    CS  10      ISO_IR 192
$ go-dicom modify -set SpecificCharacterSet='ISO_IR 100' chrRuss.dcm out.dcm
Error: modify: invalid value "SpecificCharacterSet=ISO_IR 100" for flag -set: text is read into UTF-8 and written as ISO_IR 192; SpecificCharacterSet may only be set to that

anonymize writes the same way: a file that declared another set comes out declaring ISO_IR 192, with the same characters.

Limits and gotchas

  • Files change character set when rewritten. A Latin-1 or ISO 2022 file read and written back is UTF-8. The characters are the same; the bytes and the declaration are not, and go-dicom diff shows the Specific Character Set change.
  • A guess is a guess. Undeclared non-ASCII text is read as Latin-1; a Greek or Cyrillic file that does not declare its set reads as the wrong letters. Check Warnings.
  • Undecodable bytes become U+FFFD, silently, and stay so when written.
  • Encoding is lenient by default. Use config.StrictWriting with every Encode… call whose result you will declare as a non-UTF-8 set.
  • Encode Japanese in ISO 2022 with EncodeString. EncodeWithCharset with ISO 2022 IR 13\ISO 2022 IR 87 writes Kanji as Shift_JIS bytes, not in an ESC $ B run, which other readers do not accept.
  • UN values are not decoded by GetDataset; decode one from DataElements with the file's own declaration. Text VRs the declaration does not cover (CS, UI, DA and the like) are read in the default repertoire whatever it says, as PS3.5 has it.

See also

On this page