Skip to content

Commit

Permalink
feat(String): Added a function to convert bytes to hexadecimal string…
Browse files Browse the repository at this point in the history
… representation
  • Loading branch information
macmade committed Nov 9, 2024
1 parent 0331caf commit 619164b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions SRPXX-Tests/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ XSTest( String, ToUpper )
XSTestAssertTrue( SRP::String::toUpper( "a1b2" ) == "A1B2" );
}

XSTest( String, ToHex )
{
XSTestAssertTrue( SRP::String::toHex( {}, SRP::String::HexFormat::Uppercase ) == "" );
XSTestAssertTrue( SRP::String::toHex( {}, SRP::String::HexFormat::Lowercase ) == "" );
XSTestAssertTrue( SRP::String::toHex( { 0x42 }, SRP::String::HexFormat::Uppercase ) == "42" );
XSTestAssertTrue( SRP::String::toHex( { 0x42 }, SRP::String::HexFormat::Lowercase ) == "42" );
XSTestAssertTrue( SRP::String::toHex( { 0x42, 0xFF }, SRP::String::HexFormat::Uppercase ) == "42FF" );
XSTestAssertTrue( SRP::String::toHex( { 0x42, 0xFF }, SRP::String::HexFormat::Lowercase ) == "42ff" );
}

XSTest( String, HasPrefix )
{
XSTestAssertTrue( SRP::String::hasPrefix( "abcd", "a" ) );
Expand Down
9 changes: 9 additions & 0 deletions SRPXX/include/SRPXX/String.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,22 @@
#define SRPXX_STRING_HPP

#include <string>
#include <vector>
#include <cstdint>

namespace SRP
{
namespace String
{
enum class HexFormat
{
Uppercase,
Lowercase
};

std::string toLower( const std::string & str );
std::string toUpper( const std::string & str );
std::string toHex( const std::vector< uint8_t > & data, HexFormat format = HexFormat::Uppercase );

bool hasPrefix( const std::string & str, const std::string & prefix );
}
Expand Down
23 changes: 23 additions & 0 deletions SRPXX/source/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,29 @@ namespace SRP
return ret;
}

std::string toHex( const std::vector< uint8_t > & data, HexFormat format )
{
std::string s;

for( uint8_t b: data )
{
char c[ 3 ];

if( format == HexFormat::Uppercase )
{
std::snprintf( c, 3, "%02X", b );
}
else
{
std::snprintf( c, 3, "%02x", b );
}

s.append( c );
}

return s;
}

bool hasPrefix( const std::string & str, const std::string & prefix )
{
if( str.length() < prefix.length() )
Expand Down

0 comments on commit 619164b

Please sign in to comment.