Home > Back-end >  Reading 7BitEncodedInt in Javascript
Reading 7BitEncodedInt in Javascript

Time:10-29

I am reading a binary in javascript. I think this file was written in C# and the the way binaries handle the strings in C# is a little different than how it is handled in as mentioned in

https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader.readstring?view=net-7.0

The thing is that I am not able to find any library which allows me to read C# style strings OR 7bitEncodedInt. Any suggestions on any code/package that allows me to do that?

CodePudding user response:

Actually, I found an answer in one of the libraries and modified according to what a getString would look like:

private GetString(buffer) {
    try {
      let length = this.Read7BitEncodedInt(buffer);
      if (length < 0) {
        this.toastrService.error('Error');
      }
      if (length == 0) {
        return '';
      } else {
        return buffer.getNextString(length);
      }
    }
    catch (exception){
      this.toastrService.error('Error')
    }


  }

  private Read7BitEncodedInt(buffer) {
    let count = 0, shift = 0, b = 0, i = 0;
    try {
      do {
        if (shift === 5 * 7) {
          this.toastrService.error('Error');
        }
        //Get a single byte
        b = buffer.getNextBytes(1);
        // tslint:disable-next-line:no-bitwise

        //Update the value of the int based on the byte that it belongs to(shift value)
        count |= (b & 0x7F) << shift;
        shift  = 7;
        i  ;
        // tslint:disable-next-line:triple-equals no-bitwise
        //Exit if byte is empty
      } while ((b & 0x80) != 0);
    }
    catch (exception){
      this.toastrService.error('Error message');
    }
  • Related