Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Convert signed integer to a 16-bit hex number

1,021 views
Skip to first unread message

Jordan

unread,
May 25, 2010, 11:38:22 AM5/25/10
to
I know there must be an easy way to do this, but I'm new to matlab and have not been able to figure it out and have tried searching for a solution without luck.

I need to convert a signed integer to a 16-bit sign-extended (2's complement) hex number for output to a file.

For example:

3 -> 0003
-3 -> FFFD

I've tried using dec2hex(), but it does not support negative number. I've also tried playing around with a fi object but could not quite figure out how to make that work as I needed it to.

Any suggestions?

Thanks!

Jordan

unread,
May 25, 2010, 11:39:24 AM5/25/10
to

Walter Roberson

unread,
May 25, 2010, 11:46:41 AM5/25/10
to

>> sprintf('%x', typecast(int16(-3),'uint16'))
ans =
fffd

Jordan

unread,
May 25, 2010, 11:47:20 AM5/25/10
to
Oops, sorry ignore this post, accidental double post.

"Jordan " <jmco...@hotmail.com> wrote in message <htgqvc$1e0$1...@fred.mathworks.com>...

Jordan

unread,
May 25, 2010, 11:57:21 AM5/25/10
to
Thanks! That worked great.

Walter Roberson <robe...@hushmail.com> wrote in message <BhSKn.17682$TL5....@newsfe24.iad>...

Ken Garrard

unread,
May 25, 2010, 12:15:22 PM5/25/10
to
"Jordan " <jmco...@hotmail.com> wrote in message <htgqte$qnn$1...@fred.mathworks.com>...

dec2hex((f<0)*65536+f)

Ken

Tom Bryan

unread,
May 25, 2010, 12:23:13 PM5/25/10
to

The HEX reference page in the Fixed-Point Toolbox documentation has
examples of writing and reading hex data to and from files. It is
located in the documentation at Fixed-Point Toolbox > Functions > Radix
Conversion > hex

http://www.mathworks.com/access/helpdesk/help/toolbox/fixedpoint/ref/hex.html

Using fi objects, your example would be

a = fi([3; -3], 1, 16, 0);
hex(a)

ans =

0003
fffd

The inverse also works. You can take hex strings and assign them into a
fi object.

The reference page continues the example using fprintf and fgetl to
write and read hex data to and from files.

Best wishes,
Tom Bryan
tom....@mathworks.com

0 new messages