## Loren on the Art of MATLABTurn ideas into MATLAB

Note

Loren on the Art of MATLAB has been retired and will not be updated.

# News on the Hexadecimal and Binary Numeric Fronts

I'm sure you've all heard the joke before:

  There are 10 kinds of people in the world
Those who understand binary and those who don't

By the way, the correct pronunciation of the third symbol in the first line of the joke is "two", not "ten". The hex "equivalent" is a bit rude so I won't post it here.

Well, no joke now. We've gotten serious about helping you read or specify hex and binary values now, and covering a broader range (i.e., negative hex(!) now. Let me tell you a bit more.

### Contents

#### Enter Hex and Binary Values

I don't work with hex and binary data that much myself, but there are plenty of people who do. We recently made some updates to how we can help you handle such data. Look here for the details.

We've always been able to do this:

A = 0.25
B = 3
C = 1/pi

A =
0.2500
B =
3
C =
0.3183


and these are all double values in MATLAB.

B could be represented in one of the integer forms. To do so in MATLAB, you would either convert, or you might have read in values from some other file format and specified the integer type for reading in some of the bits.

Buint8 = uint8(B)

Buint8 =
uint8
3


Now it's extremely easy to enter in hex or binary values directly into MATLAB.

D = 0X11
E = 0xF3f
F = 0b10001

D =
uint8
17
E =
uint16
3903
F =
uint8
17


Signed types are available as well.

G = 0x2As32

G =
int32
42


And then you can also represent negative numbers.

H = 0xFFs8

H =
int8
-1


These are represented in two's complement form.

Since MATLAB is storing these literals as numbers, you can use these arrays anywhere you could have used a traditional numeric array.

#### Represent Values as Text

Use dec2hex and dec2bin to convert values to the equivalent hex or binary text. These are stored in character arrays and can now handle negative values.

dec2hex(17)
dec2bin(17)
dec2hex(-17)
dec2bin(-17)

ans =
'11'
ans =
'10001'
ans =
'EF'
ans =
'11101111'


Those previous values might be good for annotation. But the best way to convert your values, especially if you have arrays of them, to hex or binary text is by using compose, where you get string output.

compose("%X", [D,E,F,G,H])

ans =
1×5 string array
"11"    "FF"    "11"    "2A"    "0"


You can also use a format specifier in reading functions to read in your data that is represented in literals, either hex or binary.

#### Bitwise Operations with Binary Values

You may be in a position where you want to operate on your binary numbers bit by bit. This is often true for some aspects of interacting with hardware (which I am hardly an expert at!). These include functions like

#### Summary

Here's more information about bitwise operations. Does this make life easier for you? Let us know here.

Published with MATLAB® R2020a

|