フィルターのクリア

writing a hex number in the right format

53 ビュー (過去 30 日間)
Adam
Adam 2012 年 2 月 29 日
hi guys
i have a problem! I need to send a message to a device like this: "e r 0x02". The hex number is just an example. It could be any number. I normally fetch the number from a GUI interface in a decimal format. In my example the decimal number will be 2.
So somehow i need to convert the decimal number into a hex format which my device can understand. This is what i have tried:
UnitType = dec2hex(str2double(get(handles.Para1,'String')))
str = sprintf('e r 0x%x',UnitType)
This is what i get:
UnitType =
2
str =
e r 0x32
But it should be 'e r 0x02' what is happening?
thx.

採用された回答

James Tursa
James Tursa 2012 年 2 月 29 日
UnitType is a string so use a string format %s instead of the hex format %x. Does your result always have to have exactly two hex digits?
  1 件のコメント
James Tursa
James Tursa 2012 年 2 月 29 日
P.S. If you take the decimal value 2 and convert it to hex you get the character '2'. The ASCII encoding of that character has a decimal value of 50, which is the same as a hex value of 32. That is why you were getting a 32 printed out in the output string str, because it was converting the character '2' to its ASCII equivalent encoding value (into a double) in order to use the %x format.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2012 年 2 月 29 日
You convert the number to hex twice.
UnitType = str2double(get(handles.Para1,'String'));
str = sprintf('e r 0x%2x', UnitType)
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 2 月 29 日
I would use
str = sprintf('e r 0x%02x', UnitType)
otherwise single-digit numbers would have a space instead of a 0.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by