fix a bug of hex

This commit is contained in:
blueloveTH 2024-02-05 15:50:13 +08:00
parent fba9d87ccd
commit faa01ac82e
3 changed files with 47 additions and 12 deletions

View File

@ -148,7 +148,7 @@ struct SStream{
SStream& operator<<(char);
SStream& operator<<(StrName);
void write_hex(unsigned char);
void write_hex(unsigned char, bool non_zero=false);
void write_hex(void*);
void write_hex(i64);
};

View File

@ -521,33 +521,48 @@ int utf8len(unsigned char c, bool suppress){
return *this;
}
void SStream::write_hex(unsigned char c){
*this << "0123456789ABCDEF"[c >> 4];
*this << "0123456789ABCDEF"[c & 0xf];
void SStream::write_hex(unsigned char c, bool non_zero){
unsigned char high = c >> 4;
unsigned char low = c & 0xf;
if(non_zero){
if(high) (*this) << "0123456789abcdef"[high];
if(high || low) (*this) << "0123456789abcdef"[low];
}else{
(*this) << "0123456789abcdef"[high];
(*this) << "0123456789abcdef"[low];
}
}
void SStream::write_hex(void* p){
if(p == nullptr){
(*this) << "0x0";
return;
}
(*this) << "0x";
uintptr_t p_t = reinterpret_cast<uintptr_t>(p);
bool non_zero = true;
for(int i=sizeof(void*)-1; i>=0; i--){
unsigned char cpnt = (p_t >> (i * 8)) & 0xff;
write_hex(cpnt);
write_hex(cpnt, non_zero);
if(cpnt != 0) non_zero = false;
}
}
void SStream::write_hex(i64 val){
if(val == 0){
(*this) << "0x0";
return;
}
if(val < 0){
(*this) << "-";
val = -val;
}
(*this) << "0x";
if(val == 0){
(*this) << "0";
return;
}
bool non_zero = true;
for(int i=56; i>=0; i-=8){
unsigned char cpnt = (val >> i) & 0xff;
if(cpnt != 0) write_hex(cpnt);
write_hex(cpnt, non_zero);
if(cpnt != 0) non_zero = false;
}
}

View File

@ -183,5 +183,25 @@ stack=[1,2,3,4]; assert f"{stack[2:]}" == '[3, 4]'
assert repr('\x1f\x1e\x1f') == '\'\\x1f\\x1e\\x1f\''
assert hex(255) == '0xFF'
assert hex(-42) == '-0x2A'
assert hex(-42) == '-0x2a'
assert hex(42) == '0x2a'
assert hex(0) == '0x0'
assert hex(1) == '0x1'
assert hex(15) == '0xf'
assert hex(16) == '0x10'
assert hex(255) == '0xff'
assert hex(256) == '0x100'
assert hex(257) == '0x101'
assert hex(17) == '0x11'
import c
assert repr(c.NULL) == '<void* at 0x0>'
assert repr(c.void_p(1)) == '<void* at 0x1>'
assert repr(c.void_p(15)) == '<void* at 0xf>'
assert repr(c.void_p(16)) == '<void* at 0x10>'
assert repr(c.void_p(255)) == '<void* at 0xff>'
assert repr(c.void_p(256)) == '<void* at 0x100>'
assert repr(c.void_p(257)) == '<void* at 0x101>'
assert repr(c.void_p(17)) == '<void* at 0x11>'