是否进行交换的条件:是本地的编码方式是否和dicom文件的编码方式不同,如是,就需要进行交换。
交换的原则:
按照格式化入dicom数据集流中的基本数据单元而定的,如是ss us,那么,就需要按照两个字节进行交换,用swap2Bytes函数;如是ul sl,那么就按照四个字节进行交换,利用函数swap4Bytes来进行。
首先是Tag,默认tag是分成两步格式化进dicom文件二进制流中,是Group Tag和Element Tag的两个部分进行。所以读取的过程中,就是要分成两步,分别把两个字节读取出来后,最后在进行数据的交换。
但是对于VR值,由于它是一个字符串,写入的时候,最基本单元是一个byte,所以不用进行大小尾的交换。
同理,字符长度也需要进行交换。
再同理,数据的值也是根据写入的最基本数据单元进行的。
以下是dcmtk中的函数:
//其中,newByteOrder:EBO_LittleEndian
// oldByteOrder: EBO_BigEndian
OFCondition swapIfNecessary(const E_ByteOrder newByteOrder,
const E_ByteOrder oldByteOrder,
void * value, const Uint32 byteLength,
const size_t valWidth)
/*
* This function swaps byteLength bytes in value if newByteOrder and oldByteOrder
* differ from each other. In case bytes have to be swapped, these bytes are seperated
* in valWidth elements which will be swapped seperately.
*
* Parameters:
* newByteOrder - [in] The new byte ordering (little or big endian).
* oldByteOrder - [in] The current old byte ordering (little or big endian).
* value - [in] Array that contains the actual bytes which might have to be swapped.
* byteLength - [in] Length of the above array.
* valWidth - [in] Specifies how many bytes shall be treated together as one element.
*/
{
/* if the two byte orderings are unknown this is an illegal call */
if(oldByteOrder != EBO_unknown && newByteOrder != EBO_unknown )
{
/* and if they differ from each other and valWidth is not 1 */
if (oldByteOrder != newByteOrder && valWidth != 1)
{
/* in case the array length equals valWidth and only 2 or 4 bytes have to be swapped */
/* we can swiftly swap these bytes by calling the corresponding functions. If this is */
/* not the case we have to call a more sophisticated function. */
if (byteLength == valWidth)
{
if (valWidth == 2)
swap2Bytes(OFstatic_cast(Uint8 *, value));
else if (valWidth == 4)
swap4Bytes(OFstatic_cast(Uint8 *, value));
else
swapBytes(value, byteLength, valWidth);
}
else
swapBytes(value, byteLength, valWidth);
}
return EC_Normal;
}
return EC_IllegalCall;
}
inline void swap2Bytes(Uint8 * toSwap)
// swaps [byte0][byte1] to [byte1][byte0]
{
Uint8 tmp = toSwap[0];
toSwap[0] = toSwap[1];
toSwap[1] = tmp;
}
inline void swap4Bytes(Uint8 * toSwap)
// swaps [byte0][byte1][byte2][byte3] to [byte3][byte2][byte1][byte0]
{
Uint8 tmp = toSwap[0];
toSwap[0] = toSwap[3];
toSwap[3] = tmp;
tmp = toSwap[1];
toSwap[1] = toSwap[2];
toSwap[2] = tmp;
}