checksum calculation, , shift byte
How to translate below code from C to COS?
void encode_value (unsigned char value, unsigned char *tx)
{
tx [1] = ((value & 0xf0) >> 4) + 0x20;
tx [0] = (value & 0x0f) + 0x20;
}
unsigned char decode_value (unsigned char *rx)
{ unsigned char temp_value = 0; temp_value = (rx [1] - 0x20) << 4;
return (temp_value + rx [0] - 0x20);
}
Product version: Caché 2018.1
Discussion (2)0
Comments
COS does not have a pointer operator so instead of "unsigned *rx and *tx" (those are char arrays) in COS you can use string variables. By the way, C counts from 0 to N-1, COS counts from 1 to N, where N ist the size of the character array respectively the length of the string.
Class DC.CtoCOS [ Abstract ]
{
/// Encode a whole string (and return a string)/// Use the below $ziswide(str) function to check for allowed charactersClassMethod Encode(str As%String) As%String
{
f i=$l(str):-1:1s$e(str,i)=$c($a(str,i)#16+32, $a(str,i)\16+32)
q str
}
/// Decode a whole string (and return a string)/// Use the below $match(str,...) function to check for allowed charactersClassMethod Decode(str As%String) As%String
{
f i=$l(str):-2:1s$e(str,i-1,i)=$c($a(str,i)-32*16+$a(str,i-1)-32)
q str
}
/// Encode a characyter into a string (variable)/// Use: do ##class(...).Encode1("A", .res)/// write res --> !$ClassMethod Encode1(chr As%String, chrs As%String)
{
i $ziswide(chr) throw##class(%Exception.General).%New("WIDE",,,chr)
s chrs=$c($a(chr)#16+32, $a(chr)\16+32)
}
/// Encode an integer (byte value) and return a string/// Use: write ##class(...).Encode2("A") --> !$ClassMethod Encode2(val As%Integer) As%String
{
i val>255throw##class(%Exception.General).%New("WIDE",,,val)
q$c($a(val)#16+32, $a(val)\16+32)
}
/// Decode two characters and return one character/// Use: write ##class(...).Decode1("!$") --> AClassMethod Decode1(chrs As%String) As%String
{
i $match(chrs,"[ -/]{2}") q$c($a(chrs,2)-32*16+$a(chrs)-32)
throw##class(%Exception.General).%New("RANGE",,,chrs)
}
/// Decode two characters and return an integer/// Use: write ##class(...).Decode2("!$") --> 65ClassMethod Decode2(chrs As%String) As%Integer
{
i $match(chrs,"[ -/]{2}") q$a(chrs,2)-32*16+$a(chrs)-32throw##class(%Exception.General).%New("RANGE",,,chrs)
}
}
Thank you very much!