c++ - Alternate way to get the Byte Length of a Hex string -
i have created function count byte length of incoming hex string, convert length hexidecimal. first assigns byte length of incoming string int, convert int string. after assigning byte length of incoming string int, check see if more 255, if is, insert 0 have 2 bytes returned, instead of 3-bits.
i follwing:
1) takes in hex string , divides number 2.
static int bytelen(std::string shexstr) { return (shexstr.length() / 2); }
2) takes in hex string, converts hex format string itoa()
static std::string bytelenstr(std::string shexstr) { //assign length int int ilen = bytelen(shexstr); std::string stemp = ""; std::string szero = "0"; std::string slen = ""; char buffer [1000]; if (ilen > 255) { //returns number passed converted hex base-16 //if on 255 insert 0 infront //so have 2 bytes instead of 3-bits stemp = itoa (ilen,buffer,16); slen = stemp.insert(0,szero); return slen; } else{ return itoa (ilen,buffer,16); } }
i convert length hexidecimal. seems work fine, looking maybe more simpler way format text in c# tostring("x2") method. c++ or method work enough?
here how in c#:
public static int bytelen(string shexstr) { return (shexstr.length / 2); } public static string bytelenstr(string shexstr) { int ilen = bytelen(shexstr); if (ilen > 255) return ilen.tostring("x4"); else return ilen.tostring("x2"); }
my logic may off bit in c++, c# method enough me in want do.
thank time.
static std::string bytelenstr(std::string& shexstr) { int ilen = bytelen(shexstr); char buffer[16]; snprintf(buffer, sizeof(buffer), (ilen > 255) ? "%04x" : "%02x", ilen); return buffer; }
snprintf formats text in buffer using format string , variable list of arguments. using %x format code convert int
argument hex string. in instance, have 2 format strings choose from:
- when
ilen > 255
, want number 4 digits long. %04x means format hex string, zero-padding @ beginning 4 places. - otherwise, want number 2 digits long. %02x means format hex string, zero-padding 2 places.
we use ternary operator select format string use. finally, ilen
passed single argument used provide value formatted function.
Comments
Post a Comment