Skip to content

Commit 3d287aa

Browse files
authored
103 magic
1 parent f71d0f1 commit 3d287aa

File tree

1 file changed

+115
-0
lines changed

1 file changed

+115
-0
lines changed

0x05-python-exceptions/103-python.c

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
#include <stdio.h>
2+
#include <Python.h>
3+
4+
/**
5+
* print_python_bytes - Prints bytes information
6+
*
7+
* @p: Python Object
8+
* Return: no return
9+
*/
10+
void print_python_bytes(PyObject *p)
11+
{
12+
char *string;
13+
long int size, i, limit;
14+
15+
setbuf(stdout, NULL);
16+
17+
printf("[.] bytes object info\n");
18+
if (!PyBytes_Check(p))
19+
{
20+
printf(" [ERROR] Invalid Bytes Object\n");
21+
setbuf(stdout, NULL);
22+
return;
23+
}
24+
25+
size = ((PyVarObject *)(p))->ob_size;
26+
string = ((PyBytesObject *)p)->ob_sval;
27+
28+
printf(" size: %ld\n", size);
29+
printf(" trying string: %s\n", string);
30+
31+
if (size >= 10)
32+
limit = 10;
33+
else
34+
limit = size + 1;
35+
36+
printf(" first %ld bytes:", limit);
37+
38+
for (i = 0; i < limit; i++)
39+
if (string[i] >= 0)
40+
printf(" %02x", string[i]);
41+
else
42+
printf(" %02x", 256 + string[i]);
43+
44+
printf("\n");
45+
setbuf(stdout, NULL);
46+
}
47+
48+
/**
49+
* print_python_float - Prints float information
50+
*
51+
* @p: Python Object
52+
* Return: no return
53+
*/
54+
void print_python_float(PyObject *p)
55+
{
56+
double val;
57+
char *nf;
58+
59+
setbuf(stdout, NULL);
60+
printf("[.] float object info\n");
61+
62+
if (!PyFloat_Check(p))
63+
{
64+
printf(" [ERROR] Invalid Float Object\n");
65+
setbuf(stdout, NULL);
66+
return;
67+
}
68+
69+
val = ((PyFloatObject *)(p))->ob_fval;
70+
nf = PyOS_double_to_string(val, 'r', 0, Py_DTSF_ADD_DOT_0, Py_DTST_FINITE);
71+
72+
printf(" value: %s\n", nf);
73+
setbuf(stdout, NULL);
74+
}
75+
76+
/**
77+
* print_python_list - Prints list information
78+
*
79+
* @p: Python Object
80+
* Return: no return
81+
*/
82+
void print_python_list(PyObject *p)
83+
{
84+
long int size, i;
85+
PyListObject *list;
86+
PyObject *obj;
87+
88+
setbuf(stdout, NULL);
89+
printf("[*] Python list info\n");
90+
91+
if (!PyList_Check(p))
92+
{
93+
printf(" [ERROR] Invalid List Object\n");
94+
setbuf(stdout, NULL);
95+
return;
96+
}
97+
98+
size = ((PyVarObject *)(p))->ob_size;
99+
list = (PyListObject *)p;
100+
101+
printf("[*] Size of the Python List = %ld\n", size);
102+
printf("[*] Allocated = %ld\n", list->allocated);
103+
104+
for (i = 0; i < size; i++)
105+
{
106+
obj = list->ob_item[i];
107+
printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name);
108+
109+
if (PyBytes_Check(obj))
110+
print_python_bytes(obj);
111+
if (PyFloat_Check(obj))
112+
print_python_float(obj);
113+
}
114+
setbuf(stdout, NULL);
115+
}

0 commit comments

Comments
 (0)