Bram Hurkmans
Bram Hurkmans

Reputation: 11

Concatenating two hex values in Javascript

I am trying to concatenate two hex values, but I have actually no idea where to begin..

As example:

a = 0x01 b = 0x23

output = 0x123

What could be the best the best solution for this particular problem? Please let me know :)

Upvotes: 1

Views: 3710

Answers (2)

Kurtis Blankenship
Kurtis Blankenship

Reputation: 1

Found that when b had a leading 0 (0x05) it would drop the zero. this fixed it for me.

var a = 0x01,
  b = 0x03;

// returns 13
console.log(
  a.toString(16) + b.toString(16)
)

// returns 0103
console.log(
  ("00"+k.toString(16)).slice(-2) + ("00"+k.toString(16)).slice(-2)
);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115262

Convert it to a string using Number#toString method and concatenate.

var a = 0x01,
  b = 0x23;

// as number
console.log(
  parseInt(a.toString(16) + b.toString(16), 16).toString(16)
)

// as string
console.log(
  a.toString(16) + b.toString(16)
)

Upvotes: 1

Related Questions