Minor update:

- Added IntToBinStr() method to convert int to binary output
This commit is contained in:
Charl Wentzel
2019-09-01 12:46:17 +02:00
parent 55168dece2
commit cff2d2712a
2 changed files with 38 additions and 2 deletions

View File

@@ -119,6 +119,40 @@ char * BytesToBinStr( const char * Bytes, const int Len, const char * Separator,
}
//---------------------------------------------------------------------------
char * IntToBinStr( const int Bytes, const int Len, const char * Separator, char * OutBuf )
{
char * TempBuf;
char * BufPos;
bool First = true;
char SepLen = (Separator)? strlen(Separator) : 0;
u_int8_t Byte;
// Select/create output buffer
if (!OutBuf) {
TempBuf = ReturnStr;
}
else {
// if (!*OutBuf)
// *OutBuf = (char*)malloc( Len*(8+SepLen)+1 );
// TempBuf = *OutBuf;
TempBuf = OutBuf;
}
BufPos = TempBuf;
// Print each byte as 8-bit binary
for (int i=Len-1; i>=0; i--) {
Byte = (Bytes >> (i*8)) & 0xFF;
sprintf( BufPos, "%s%c%c%c%c%c%c%c%c", ((First || !Separator)? "" : Separator),
(Byte & 0x80)?'1':'0', (Byte & 0x40)?'1':'0', (Byte & 0x20)?'1':'0', (Byte & 0x10)?'1':'0',
(Byte & 0x08)?'1':'0', (Byte & 0x04)?'1':'0', (Byte & 0x02)?'1':'0', (Byte & 0x01)?'1':'0' );
BufPos += (First)? 8 : 8+SepLen;
First = false;
}
*BufPos = 0;
return TempBuf;
}
//---------------------------------------------------------------------------
char * HexStrToBytes( const char * Str, const int Len, const char * Separator, char * OutBuf )
{
char * TempBuf;

View File

@@ -18,8 +18,10 @@
// Convert raw bytes to string
char * BytesToSafeStr( const char * Bytes, const int Len, const bool NoCrLf = false, const char SpecChar = '.', char * OutBuf = NULL );
char * BytesToHexStr( const char * Bytes, const int Len, const char *Separator = " ", char * OutBuf = NULL );
char * BytesToBinStr( const char * Bytes, const int Len, const char *Separator = " ", char * OutBuf = NULL );
char * BytesToHexStr( const char * Bytes, const int Len, const char * Separator = " ", char * OutBuf = NULL );
char * BytesToBinStr( const char * Bytes, const int Len, const char * Separator = " ", char * OutBuf = NULL );
char * IntToBinStr( const int Bytes, const int Len, const char * Separator = " ", char * OutBuf = NULL );
// Convert string to raw bytes
inline u_int8_t HexToInt( char Digit ) {