Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions src/core/format/Convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,7 @@ export class Convert {
* @return {string}
*/
public static utf8ToHex = (input: string): string => {
const rawString = Convert.rstr2utf8(input);
let result = '';
for (let i = 0; i < rawString.length; i++) {
result += rawString.charCodeAt(i).toString(16).padStart(2, '0');
}
return result.toUpperCase();
return Buffer.from(input, 'utf-8').toString('hex').toUpperCase();
};

/**
Expand Down
10 changes: 1 addition & 9 deletions src/model/message/Message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,7 @@ export abstract class Message {
* @returns {string}
*/
public static decodeHex(hex: string): string {
let str = '';
for (let i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
try {
return decode(str);
} catch (e) {
return str;
}
return Buffer.from(hex, 'hex').toString();
}

/**
Expand Down
8 changes: 8 additions & 0 deletions test/core/format/Convert.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,14 @@ describe('convert', () => {
expect(actual).to.equal('E58588E7A7A6E585A9E6BCA2');
});

it('utf8 text containing emoji to hex', () => {
// Act:
const actual = convert.utf8ToHex('😀こんにちは😀');

// Assert:
expect(actual).to.equal('F09F9880E38193E38293E381ABE381A1E381AFF09F9880');
});

it('utf8 text to hex with control char', () => {
// Act:
const actual = convert.utf8ToHex(String.fromCodePoint(0x0f) + ' Hello World!');
Expand Down
5 changes: 5 additions & 0 deletions test/model/message/Message.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,9 @@ describe('Message', () => {
const hex = '746573742D6D657373616765';
expect(Message.decodeHex(hex)).to.be.equal('test-message');
});

it('should decode hex string (emoji)', () => {
const hex = 'F09F9880E38193E38293E381ABE381A1E381AFF09F9880';
expect(Message.decodeHex(hex)).to.be.equal('😀こんにちは😀');
});
});