Skip to content

Commit dd21055

Browse files
authored
change message Encoding/Decoding method (#632)
1 parent c6fda5c commit dd21055

File tree

4 files changed

+15
-15
lines changed

4 files changed

+15
-15
lines changed

src/core/format/Convert.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,7 @@ export class Convert {
165165
* @return {string}
166166
*/
167167
public static utf8ToHex = (input: string): string => {
168-
const rawString = Convert.rstr2utf8(input);
169-
let result = '';
170-
for (let i = 0; i < rawString.length; i++) {
171-
result += rawString.charCodeAt(i).toString(16).padStart(2, '0');
172-
}
173-
return result.toUpperCase();
168+
return Buffer.from(input, 'utf-8').toString('hex').toUpperCase();
174169
};
175170

176171
/**

src/model/message/Message.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,7 @@ export abstract class Message {
2626
* @returns {string}
2727
*/
2828
public static decodeHex(hex: string): string {
29-
let str = '';
30-
for (let i = 0; i < hex.length; i += 2) {
31-
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
32-
}
33-
try {
34-
return decode(str);
35-
} catch (e) {
36-
return str;
37-
}
29+
return Buffer.from(hex, 'hex').toString();
3830
}
3931

4032
/**

test/core/format/Convert.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,14 @@ describe('convert', () => {
272272
expect(actual).to.equal('E58588E7A7A6E585A9E6BCA2');
273273
});
274274

275+
it('utf8 text containing emoji to hex', () => {
276+
// Act:
277+
const actual = convert.utf8ToHex('😀こんにちは😀');
278+
279+
// Assert:
280+
expect(actual).to.equal('F09F9880E38193E38293E381ABE381A1E381AFF09F9880');
281+
});
282+
275283
it('utf8 text to hex with control char', () => {
276284
// Act:
277285
const actual = convert.utf8ToHex(String.fromCodePoint(0x0f) + ' Hello World!');

test/model/message/Message.spec.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,9 @@ describe('Message', () => {
5050
const hex = '746573742D6D657373616765';
5151
expect(Message.decodeHex(hex)).to.be.equal('test-message');
5252
});
53+
54+
it('should decode hex string (emoji)', () => {
55+
const hex = 'F09F9880E38193E38293E381ABE381A1E381AFF09F9880';
56+
expect(Message.decodeHex(hex)).to.be.equal('😀こんにちは😀');
57+
});
5358
});

0 commit comments

Comments
 (0)