0

How is it possible in javascript to obtain the b Buffer in a way simpler than the following?

  var num=6553599

  var a = new Buffer(4); 
  a.writeInt32LE(num); 

  var up=a.readUInt8(2); 
  var mid=a.readUInt8(1);   
  var low=a.readUInt8(0);    

  var b=new Buffer(6);
  b.writeUInt8('T'.charCodeAt(0),0);      
  b.writeUInt8(up  ,1); 
  b.writeUInt8(mid ,2);
  b.writeUInt8(low ,3); 
  b.writeUInt8(0   ,4); 
  b.writeUInt8(1   ,5); 

1 Answer 1

1

If performance is not an issue you can use the string representation of buffers to work with them more easily.

Usually I prefer the hex representation of buffers since they're easier to read and it is easy to count bytes this way.

var bConcat = (a, b) => new Buffer(a.toString("hex") + b.toString("hex"), "hex");
var reducer = (acc, current)=> bConcat(acc, current);
var num=6553599
var a = new Buffer(4);
var t = 'T'.charCodeAt(0);
a.writeInt32LE(num); 
var head = new Buffer(t.toString(16), "hex");
var tail = new Buffer("0001", "hex");
var b = [head, a.slice(0,3).reverse(), tail].reduce(reducer);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.