简体   繁体   中英

How can I convert a string that represent a HEX octet in postgresql to binary?

I have a mac adress stored with type mac address in postgresql. I need to convert the first octet in the information about I/G bit and U/L bit ( more infos ).

Example: mac address is AA-BB-CC-DD-EE-FF . The first Octet is then AA . Converted to Binary: 0101 01010 . The last bit represents I/G: 0. The second from right to left is the U/L bit: 1.

How can I do this in a postgresql query?

This is what I have so far:

select id, mac, left(mac::text,2) as octet 
from mytable

The return is:

id,mac,octet
13,aa:XX:XX:XX:XX:XX,aa

I also tried left(mac::text,2)::integer as integer , but I get the error message [22P02] ERROR: invalid input syntax for integer: "aa"

The result I want is the following:

id, mac, octet, binary, ig_bit, ul_bit
13, aa:XX:XX:XX:XX:XX,aa, 1010 1010, 0, 1

So I have isolated the first bit, however, the format is 'text' and I can't convert it to integer or binary.

Use bit strings:

with my_data(mac) as (
    values ('AA-BB-CC-DD-EE-FF'::macaddr)
)

select 
    mac,
    ('x' || left(mac::text, 2))::bit(8) as octet,
    substr(('x' || left(mac::text, 2))::bit(8)::text, 8, 1) as ig_bit,
    substr(('x' || left(mac::text, 2))::bit(8)::text, 7, 1) as ul_bit
from my_data

        mac        |  octet   | ig_bit | ul_bit 
-------------------+----------+--------+--------
 aa:bb:cc:dd:ee:ff | 10101010 | 0      | 1
(1 row)

You can also use the function get_bit() , eg:

with my_data(mac) as (
    values ('AA-BB-CC-DD-EE-FF'::macaddr)
),
octet as (
    select mac, ('x' || left(mac::text, 2))::bit(8) as binary_octet
    from my_data
)

select 
    mac,
    binary_octet,
    get_bit(binary_octet, 7) as ig_bit,
    get_bit(binary_octet, 6) as ul_bit
from octet

Note, that the index of the leftmost bit is 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM