From f1cc35635cc879696c4343c0566916052f459dfd Mon Sep 17 00:00:00 2001 From: Unbewohnte Date: Fri, 16 Jul 2021 16:19:19 +0300 Subject: [PATCH] =?UTF-8?q?=E1=9B=9C=20Added=20some=20core=20util=20functi?= =?UTF-8?q?ons=20=E1=9B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/bits.go | 6 ++++++ util/bits_test.go | 14 ++++++++++++++ util/conversion.go | 36 +++++++++++++++++++++++------------- util/conversion_test.go | 26 ++++++++++++++++++-------- 4 files changed, 61 insertions(+), 21 deletions(-) create mode 100644 util/bits.go create mode 100644 util/bits_test.go diff --git a/util/bits.go b/util/bits.go new file mode 100644 index 0000000..115560a --- /dev/null +++ b/util/bits.go @@ -0,0 +1,6 @@ +package util + +// Tells if bit is set in given byte +func IsSet(n byte, bitN int) bool { + return n&byte(1<> 25 //00000000 00000000 00000000 01101010 - bytes = append(bytes, byte(shifted)) - } + // skip 4 0`ed bits + gInt = gInt << 4 + + // int32 == 4 bytes + for i := 0; i < 32/8; i++ { + // get first 7 bits + first7Bits := gInt & first7BitsMask - return bytes + // shift captured bits to the beginning + first7Bits = first7Bits >> (3*8 + 1) + + b := byte(first7Bits) + synchsafeIBytes = append(synchsafeIBytes, b) + + // prepare next 7 bits for the next iteration + gInt = gInt << 7 + } + return synchsafeIBytes } // Converts given bytes into string, ignoring the first 31 non-printable ASCII characters. diff --git a/util/conversion_test.go b/util/conversion_test.go index 9736e0b..01326b0 100644 --- a/util/conversion_test.go +++ b/util/conversion_test.go @@ -25,13 +25,23 @@ func TestDecodeText(t *testing.T) { } } -// func TestIntToBytesFirstBitZeroed(t *testing.T) { -// var testint uint32 = 123456 +func TestIntToBytesSynchsafe(t *testing.T) { + testInts := []uint32{ + 1234, + 12, + 1, + 0, + 99999, + 87654321, + } + + for _, testInt := range testInts { + synchSafeBytes := IntToBytesSynchsafe(testInt) -// intbytes := IntToBytesFirstBitZeroed(testint) + synchsafeInt := BytesToIntSynchsafe(synchSafeBytes) -// if BytesToIntIgnoreFirstBit(intbytes) != testint { -// t.Errorf("IntToBytesFirstBitZeroed failed: expected to get %v; got %v", -// testint, BytesToIntIgnoreFirstBit(intbytes)) -// } -// } + if synchsafeInt != testInt { + t.Errorf("BytesToIntSynchsafe failed: expected to get %d; got %d", testInt, synchsafeInt) + } + } +}